写了个程序,发现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); }
}
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); }
}
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()。。