
常用软件类: |
|杀毒安全 | |联络聊天 | |网络软件 | |多媒体类 | |系统工具 | |图形图像 | |系统工具 | |应用软件 | |行业软件 |
开发设计类: |
|动画制作 | |图像处理 | |3D设计 | |操作系统 | |站长学院 | |网络相关 | |WEB设计 | |数据库类 | |程序开发 |
| String s = new String ("Text here"); |
| String temp = "Text here"; String s = new String (temp); |
| String s = "Text here"; |
| import java.awt.Dimension; /***Example class.The x and y values should never*be negative.*/ public class Example{ private Dimension d = new Dimension (0, 0); public Example (){ } /*** Set height and width. Both height and width must be nonnegative * or an exception is thrown.*/ public synchronized void setValues (int height,int width) throws IllegalArgumentException{ if (height < 0 || width < 0) throw new IllegalArgumentException(); d.height = height; d.width = width; } public synchronized Dimension getValues(){ // Ooops! Breaks encapsulation return d; } } |
| Example ex = new Example(); Dimension d = ex.getValues(); d.height = -5; d.width = -10; |
| public synchronized Dimension getValues(){ return new Dimension (d.x, d.y); } |
| /*** Example class.The value should never * be negative.*/ public class Example{ private Integer i = new Integer (0); public Example (){ } /*** Set x. x must be nonnegative* or an exception will be thrown*/ public synchronized void setValues (int x) throws IllegalArgumentException{ if (x < 0) throw new IllegalArgumentException(); i = new Integer (x); } public synchronized Integer getValue(){ // We can’t clone Integers so we makea copy this way. return new Integer (i.intValue()); } } |
| public synchronized Integer getValue(){ // ’i’ is immutable, so it is safe to return it instead of a copy. return i; } |
| public class Example{ private int[] copy; /*** Save a copy of ’data’. ’data’ cannot be null.*/ public void saveCopy (int[] data){ copy = new int[data.length]; for (int i = 0; i < copy.length; ++i) copy[i] = data[i]; } } |
| void saveCopy (int[] data){ try{ copy = (int[])data.clone(); }catch (CloneNotSupportedException e){ // Can’t get here. } } |
如果你经常克隆数组,编写如下的一个工具方法会是个好主意: