Object Clone Shallow copy doesn't change variable

I tried to clone an object and change member functions of new clonned object. If it is shallow copy and according to wiki page, shallow copy and original object point to same object then , it should change the variable value.

    CloneExample obj1=new CloneExample();
    CloneExample obj2=(CloneExample) obj1.clone();
    obj1.a=2;
    obj1.c='a';
    System.out.println("obj1 real "+obj1.a+" "+obj1.c);
    System.out.println("obj2 real "+obj2.a+" "+obj2.c);
    obj2.a=99;
    obj2.c='z';
    System.out.println("obj2 after change "+obj2.a+" "+obj2.c);
    System.out.println("obj1 after change "+obj1.a+" "+obj1.c);
    System.out.println("obj1="+obj1+" obj2="+obj2);

If this clone is shallow copy, then obj2 and Obj1 point to same reference obj, altering obj2 should reflect in obj1. It doesn't happen. Can any one explain (I understand clone is designed to give us copy of object, but if it is shallow copy then why we need shallow copy?, we should always go for deep copy). Thank you.


When you call object.clone(), new object is created. So as a result you get reference to this object. Object with only primitive type field are cloning perfectly. As a result you get a full independent from your obj1 copy. But if your object has fields with references, you need to do a deep cloning.


why do you think clone is a shallow copy? see here: http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#clone()

As it says - what clone does is implementation dependent. Also a 'shallow copy' doesn't simply create a new reference to the same object - generally it means that a new instance is created with the same internal members as the object copied-from. But if you change a member variable of the new obj to point to something new, you are not changing member vars of original obj.


Shallow copy of obj1 creates another instance obj2 of your CloneExample class (obj1!=obj2). They don't share value members.

But if our class contained a reference type, for example java.util.Date , then changing it's value would be reflected in both object if they shared reference to that java.util.Date .

In Java, what is a shallow copy?

链接地址: http://www.djcxy.com/p/6968.html

上一篇: 深度克隆对象后清除主键

下一篇: 对象克隆浅拷贝不会改变变量