简体   繁体   English

如果将 clone() 值设为零,则原始 object 值也将更改为零

[英]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.我正在使用 clone() 方法复制我的 object。 But when there is modification in the copy the original object is also modified.但是当副本中有修改时,原来的 object 也被修改了。 I have tried to replicate my issue in the following example.我试图在以下示例中复制我的问题。 Here are 2 classes ClassA and ClassB.这里有 2 个类 ClassA 和 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 //这里是ClassA,其中包含main方法并使用克隆

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?现在如何保留原来的 object 值? 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.在我的原始代码中,我必须稍后使用原始 object 位值进行更多计算,并且复制的 object 位值将为 0。谢谢。

Don't set bit to the same byte[] as the original object, instead clone it as well:不要将bit设置为与原始 object 相同的byte[] ,而是克隆它:

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() .此外,您不需要设置num ,因为它已经在super.clone()返回的 object 上正确设置。

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

These two lines of code are (a) redundant and (b) wrong.这两行代码是 (a) 多余的和 (b) 错误的。 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.如果您只想要克隆中的原始字段值,则根本不需要它,因为 super.clone() 已经为您完成了。 If your aim is to return an independently-valued object.如果您的目标是返回一个独立值的 object。 As bit[] is an array, ie an Object, you should clone it too.由于 bit[] 是一个数组,即 Object,你也应该克隆它。

You are not cloning your bit array.你没有克隆你的bit组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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