clone 方法创建调用它的对象的一个复制副本! 所以副本改变了引应用对象的内容!对应的源对象不会被被改变 引用就可以, so easy
class Father { int age; Son son; }class Son { int age; } 假设有:Father father = new Father(); 当clone father时,产生副本father_1。 father_1.age是father.age的副本,它们存放在不同的内存区域。 father_1.son也是father.son的副本,但它们的内容都是指向同一Son对象的reference。 father_1.age改变时,不会影响father.age。 但father_1.son.age改变时,father.son.age当然也变了。
下面的例子可以帮助你理解clone. //TestClone.javaimport java.util.*;public class TestClone { static public void main (String args[]){ Vector v = new Vector(); v.add(new StringBuffer("Original")); Vector cv=(Vector)v.clone();
不能一概而论,要看类的Clone方法是怎么实现的 你可以在Clone中实现任意深度的复制。 Object类的clone()是field-for-field 复制,即引用变量将只复制变量本身而不复制其引用的对象。但是你可以覆盖Object类的clone() 如: public T implements Cloneable{ Integer interger = new Integer(0); public Object clone(){ T temp= new T(); temp.integer = this.integer.clone(); return temp; } }
你对它的副本操作不会影响源对象
而当clone复杂对象时,如 Vector时如果你改变副本的elements,那么源对象的elements也会改变
请问有没有例子阿!
所以副本改变了引应用对象的内容!对应的源对象不会被被改变
引用就可以, so easy
int age;
Son son;
}class Son {
int age;
}
假设有:Father father = new Father();
当clone father时,产生副本father_1。
father_1.age是father.age的副本,它们存放在不同的内存区域。
father_1.son也是father.son的副本,但它们的内容都是指向同一Son对象的reference。
father_1.age改变时,不会影响father.age。
但father_1.son.age改变时,father.son.age当然也变了。
//TestClone.javaimport java.util.*;public class TestClone {
static public void main (String args[]){
Vector v = new Vector();
v.add(new StringBuffer("Original")); Vector cv=(Vector)v.clone();
System.out.println("v="+v);
System.out.println("v.clone()="+cv);
cv.add(new StringBuffer("Cloned Added"));
System.out.println("\nafter Cloned Added:");
System.out.println("v="+v+"");
System.out.println("v.clone()="+cv+"");
StringBuffer sb=(StringBuffer)cv.elementAt(0);
// StringBuffer sb=(StringBuffer)v.elementAt(0);
sb.append(" Modified");
System.out.println("\nafter Cloned Element Modified:");
System.out.println("v="+v+"");
System.out.println("v.clone()="+cv+"");
}}
http://www.csdn.net/Expert/topic/418/418708.shtm
里面已经讨论很多了!!!
你可以在Clone中实现任意深度的复制。
Object类的clone()是field-for-field 复制,即引用变量将只复制变量本身而不复制其引用的对象。但是你可以覆盖Object类的clone()
如:
public T implements Cloneable{
Integer interger = new Integer(0);
public Object clone(){
T temp= new T();
temp.integer = this.integer.clone();
return temp;
}
}