简体   繁体   中英

If clone() value is made zero the original object value also changes to zero

I am making a copy of my object by using clone() method. But when there is modification in the copy the original object is also modified. I have tried to replicate my issue in the following example. Here are 2 classes ClassA and ClassB.

public class ClassB implements Cloneable
{
    int num = 0;

    byte[] bit = new byte[1];

     //Getters and setters have been removed due to space constraint

            public Object clone() 
    {
        try
        {   
          ClassB obj = (ClassB)super.clone();

          obj.setNum(this.num);
               obj.setBit(this.bit);

          return obj;
        } catch (CloneNotSupportedException e) {
                return null;              }
    }
}

//Here is ClassA whioch contains the main method and uses clone

public class ClassA {

    public void cloneMethod(){

        ClassB objB = new ClassB();
        objB.bit[0] = (byte)0x8;
        objB.setNum(5);     

        ClassB objCopy = null;
        objCopy = (ClassB) objB.clone();

        if(objCopy.bit[0] != (byte)0x0)
        {
            objCopy.bit[0] = 0;
        }

        System.out.println(objB.bit[0]); //At this point the original object    value is also modified.

    }

    public static void main(String args[])
    {
        ClassA a = new ClassA();
        a.cloneMethod();
    }

}

Now how to retain the original object value? I know clone has certain disadvantages. I have tried with new key word also but it doesnt help.Please suggest. in my original code I have to use the original object bit value later for some more calculation and the copy object bit value will be 0. Thanks.

Don't set bit to the same byte[] as the original object, instead clone it as well:

obj.bit = this.bit.clone();

Also, you don't need to set num , because that will already be set correctly on the object returned by super.clone() .

obj.setNum(this.num);
obj.setBit(this.bit);

These two lines of code are (a) redundant and (b) wrong. If you just want the original field values in the clone you don't need this at all, because super.clone() has already done it for you. If your aim is to return an independently-valued object. As bit[] is an array, ie an Object, you should clone it too.

You are not cloning your bit array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM