常范的对象克隆错误

来源:互联网 发布:马绍信 知乎 编辑:程序博客网 时间:2024/05/16 15:37

一、常见错误1# :多次拷贝字符串

测试所不能发现的一个错误是生成不可变(immutable)对象的多份拷贝。不可变对象是不可改变的,因此不需要拷贝它。最常用的不可变对象是String。

如果你必须改变一个String对象的内容,你应该使用StringBuffer。下面的代码会正常工作:

  1. String s = new String ("Text here"); 

但是,这段代码性能差,而且没有必要这么复杂。你还可以用以下的方式来重写上面的代码:

  1. String temp = "Text here";   
  2. String s = new String (temp); 

但是这段代码包含额外的String,并非完全必要。更好的代码为:

  1. String s = "Text here"

二、常见错误2#: 没有克隆(clone)返回的对象

封装(encapsulation)是面向对象编程的重要概念。不幸的是,Java为不小心打破封装提供了方便——Java允许返回私有数据的引用(reference)。下面的代码揭示了这一点:

  1.  
  2. import java.awt.Dimension;   
  3. /***Example class.The x and y values should never*be negative.*/   
  4. public class Example{   
  5.   private Dimension d = new Dimension (00);   
  6.   public Example (){ }  
  7.   /*** Set height and width. Both height and width must be nonnegative * 
  8. or an exception is thrown.*/   
  9.   public synchronized void setValues (int height,int width) throws IllegalArgumentException{   
  10. if (height < 0 || width < 0)   
  11.   throw new IllegalArgumentException();   
  12.   d.height = height;   
  13. d.width = width;   
  14.   }  
  15.   public synchronized Dimension getValues(){   
  16. // Ooops! Breaks encapsulation   
  17. return d;   
  18.   }   

Example类保证了它所存储的height和width值永远非负数,试图使用setValues()方法来设置负值会触发异常。不幸的是,由于getValues()返回d的引用,而不是d的拷贝,你可以编写如下的破坏性代码:

  1. Example ex = new Example();   
  2. Dimension d = ex.getValues();   
  3. d.height = -5;   
  4. d.width = -10

现在,Example对象拥有负值了!如果getValues() 的调用者永远也不设置返回的Dimension对象的width 和height值,那么仅凭测试是不可能检测到这类的错误。

不幸的是,随着时间的推移,客户代码可能会改变返回的Dimension对象的值,这个时候,追寻错误的根源是件枯燥且费时的事情,尤其是在多线程环境中。

更好的方式是让getValues()返回拷贝:

  1. public synchronized Dimension getValues(){   
  2. return new Dimension (d.x, d.y);   

现在,Example对象的内部状态就安全了。调用者可以根据需要改变它所得到的拷贝的状态,但是要修改Example对象的内部状态,必须通过setValues()才可以。

三、常见错误3#:不必要的克隆

我们现在知道了get方法应该返回内部数据对象的拷贝,而不是引用。但是,事情没有绝对:

  1. /*** Example class.The value should never * be negative.*/   
  2. public class Example{   
  3.   private Integer i = new Integer (0);   
  4.   public Example (){ }  
  5.   /*** Set x. x must be nonnegative* or an exception will be thrown*/   
  6.   public synchronized void setValues (int x) throws IllegalArgumentException{   
  7. if (x < 0)   
  8.   throw new IllegalArgumentException();   
  9.   i = new Integer (x);   
  10.   }  
  11.   public synchronized Integer getValue(){   
  12. // We can’t clone Integers so we makea copy this way.   
  13. return new Integer (i.intValue());   
  14.   }   

这段代码是安全的,但是就象在错误1#那样,又作了多余的工作。Integer对象,就象String对象那样,一旦被创建就是不可变的。因此,返回内部Integer对象,而不是它的拷贝,也是安全的。

方法getValue()应该被写为:

  1. public synchronized Integer getValue(){   
  2. // ’i’ is immutable, so it is safe to return it instead of a copy.   
  3. return i;   

Java程序比C++程序包含更多的不可变对象。JDK 所提供的若干不可变类包括:

  • Boolean
  • Byte
  • Character
  • Class
  • Double
  • Float
  • Integer
  • Long
  • Short
  • String
  • 大部分的Exception的子类

四、常见错误4# :自编代码来拷贝数组

Java允许你克隆数组,但是开发者通常会错误地编写如下的代码,问题在于如下的循环用三行做的事情,如果采用Object的clone方法用一行就可以完成:

  1. public class Example{   
  2. private int[] copy;   
  3. /*** Save a copy of ’data’. ’data’ cannot be null.*/   
  4. public void saveCopy (int[] data){   
  5. copy = new int[data.length];   
  6. for (int i = 0; i < copy.length; ++i)   
  7. copy[i] = data[i];   
  8. }   

这段代码是正确的,但却不必要地复杂。saveCopy()的一个更好的实现是:

  1. void saveCopy (int[] data){   
  2. try{   
  3. copy = (int[])data.clone();   
  4. }catch (CloneNotSupportedException e){   
  5. // Can’t get here. }   

如果你经常克隆数组,编写如下的一个工具方法会是个好主意:

  1. static int[] cloneArray (int[] data){   
  2. try{   
  3. return(int[])data.clone();   
  4. }catch(CloneNotSupportedException e){   
  5. // Can’t get here.   
  6. }   

这样的话,我们的saveCopy看起来就更简洁了:

  1. void saveCopy (int[] data){   
  2. copy = cloneArray ( data); } 

五、常见错误5#:拷贝错误的数据

有时候程序员知道必须返回一个拷贝,但是却不小心拷贝了错误的数据。由于仅仅做了部分的数据拷贝工作,下面的代码与程序员的意图有偏差:

  1. import java.awt.Dimension;   
  2. /*** Example class. The height and width values should never * be   
  3. negative. */   
  4. public class Example{   
  5. static final public int TOTAL_VALUES = 10;   
  6. private Dimension[] d = new Dimension[TOTAL_VALUES];   
  7. public Example (){ }  
  8. /*** Set height and width. Both height and width must be nonnegative * or
  9.  an exception will be thrown. */   
  10. public synchronized void setValues (int index, int height, int width) 
  11. throws IllegalArgumentException{   
  12. if (height < 0 || width < 0)   
  13. throw new IllegalArgumentException();   
  14. if (d[index] == null)   
  15. d[index] = new Dimension();   
  16. d[index].height = height;   
  17. d[index].width = width;   
  18. }  
  19. public synchronized Dimension[] getValues()   
  20. throws CloneNotSupportedException{   
  21. return (Dimension[])d.clone();   
  22. }   

这儿的问题在于getValues()方法仅仅克隆了数组,而没有克隆数组中包含的Dimension对象,因此,虽然调用者无法改变内部的数组使其元素指向不同的Dimension对象,但是调用者却可以改变内部的数组元素(也就是Dimension对象)的内容。方法getValues()的更好版本为:

  1. public synchronized Dimension[] getValues() throws CloneNotSupportedException{   
  2. Dimension[] copy = (Dimension[])d.clone();   
  3. for (int i = 0; i < copy.length; ++i){   
  4. // NOTE: Dimension isn’t cloneable.   
  5. if (d != null)   
  6. copy[i] = new Dimension (d[i].height, d[i].width);   
  7. }  
  8. return copy;   

在克隆原子类型数据的多维数组的时候,也会犯类似的错误。原子类型包括int,float等。简单的克隆int型的一维数组是正确的,如下所示:

  1. public void store (int[] data) throws CloneNotSupportedException{   
  2. this.data = (int[])data.clone();   
  3. // OK   

拷贝int型的二维数组更复杂些。Java没有int型的二维数组,因此一个int型的二维数组实际上是一个这样的一维数组:它的类型为int[]。简单的克隆int[][]型的数组会犯与上面例子中getValues()方法第一版本同样的错误,因此应该避免这么做。下面的例子演示了在克隆int型二维数组时错误的和正确的做法:

  1. public void wrongStore (int[][] data) throws CloneNotSupportedException{   
  2.   this.data = (int[][])data.clone(); // Not OK!   
  3. }  
  4. public void rightStore (int[][] data){   
  5.   // OK!   
  6.   this.data = (int[][])data.clone();   
  7.   for (int i = 0; i < data.length; ++i){   
  8. if (data != null)   
  9.   this.data[i] = (int[])data[i].clone();   
  10.   }   
以上都是转载的东西,作为提醒自己以后注意点东西,最后加点自己的看法,虽然肤浅
对于上面的#2, 3, 5 点,我认为主要问题就是getValue() 获取的是对象引用, 在Effective Java 上面有比较详细的讲述,可不可写一个工具类,实现对象的深度拷贝呢,这样这些问题就不存在了。
对于#4, Arrays已经存在这样的拷贝数组方法了,可以不去发明新的轮子吧.

原创粉丝点击