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()
.