写了个程序,发现Vector直接调用clone只是浅拷贝,难道只能一个一个去拷贝么?
public class SimulationInstanceData implements Cloneable {
/* (non-Javadoc)
 * @see java.lang.Object#clone()
 */
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
// SimulationInstanceData sd = (SimulationInstanceData) this.clone();
return super.clone();//sd;//super.clone();
} int arrivingTime; // in seconds,the time after previous workflow instance
String SpecificationID; //
int order; // the order of arriving
String InstanceID;

public SimulationInstanceData(){
this.arrivingTime = 1;
this.SpecificationID = "g";
this.order = 3;
this.InstanceID = "ggg";
}

public static void main(String[] arg) throws CloneNotSupportedException{
Vector<SimulationInstanceData> sv1 = new Vector();
Vector<SimulationInstanceData> sv2 = new Vector();
for(int i=0; i<4 ;i++){
SimulationInstanceData sd = new SimulationInstanceData();
sv1.add(sd);
}
sv2 = (Vector<SimulationInstanceData>) sv1.clone(); System.out.println(sv1);
System.out.println(sv2);

sv2.removeAllElements();

for(int i=0; i<4 ;i++){
SimulationInstanceData sd = (SimulationInstanceData) sv1.elementAt(i).clone();//new SimulationInstanceData();
sv2.add(sd);
}

System.out.println(sv1);
System.out.println(sv2); }
}

解决方案 »

  1.   

    Object 的 clone就是浅拷贝,深拷贝是实现序列化接口...
      

  2.   

    恩,谢谢,再问两个问题。1 如果 Object 的 clone 是浅的,那和直接等于有什么区别呢?2 如果重写 clone 这个方法,对于vector来说,也是要一个一个将旧的vector加到新的vector中去。但是 clone这个方法是 protected 属性,难道还要改属性不成?
      

  3.   

    1:
    Object的clone的注释:
    Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression:  x.clone() != x
    will be true, and that the expression: 
     x.clone().getClass() == x.getClass()
    will be true, but these are not absolute requirements. While it is typically the case that: 
     x.clone().equals(x)
    will be true, this is not an absolute requirement. 2:不用改属性,提供一个公有方法直接调用clone()。。