简体   繁体   English

java避免对象通过引用传递

[英]java avoid Objects pass by reference

I'm facing problem with object cloning in java. 我在Java中遇到对象克隆问题。

public class TestClass {

private int count;
private List<Integer> list;
public final int getCount() {
    return count;
}
public final void setCount(int count) {
    this.count = count;
}
public final List<Integer> getList() {
    return list;
}
public final void setList(List<Integer> list) {
    this.list = list;
}

}


public class Main {

public static void main(String[] args) {
TestClass obj = new TestClass();
obj.setCount(5);
List<Integer> temp = new ArrayList<Integer>();
temp.add(1);
temp.add(2);
obj.setList(temp);

TestClass newObj= obj;


System.out.println(newObj.getList().size());
obj.getList().add(3);
System.out.println(newObj.getList().size());


}

}

The output I'm getting here is 2,3. 我在这里得到的输出是2,3。 But my desired output is 2,2 but since java assign reference of "obj" to newObj. 但是我想要的输出是2,2,但是由于java将“ obj”的引用分配给newObj。 Is there anyway to avoid this? 反正有避免这种情况吗? I have seen that serialize the object and deserialize it will give brand new reference to "newObj". 我已经看到序列化对象并反序列化它会给“ newObj”提供全新的引用。 But is there anyother efficient ways? 但是还有其他有效的方法吗?

First, you aren't actually cloning which in java means you use the object.clone() method. 首先,您实际上并没有进行克隆 ,这意味着在Java中您将使用object.clone()方法。 clone makes a shallow copy of an object. clone复制对象的浅表副本。 You just made a 2nd reference to the same object. 您刚刚对同一对象进行了第二次引用。

In your code, calling 在您的代码中,调用

obj.getList().add(3);

Is the same as 是相同的

newObj.getList().add(3);

Which is why it is printing the way it is. 这就是为什么它按原样打印。

You need to make a deep copy of the object so not only is the instance of TestClass different, but all the fields are different too. 您需要制作对象的深层副本,因此不仅TestClass的实例不同,而且所有字段也不同。

The easiest way to do this is to make a copy method and/or a copy constructor 最简单的方法是制作一个复制方法和/或一个复制构造函数

public class TestClass{
      public TestClass(){
      }

      //copy constructor
      public TestClass( TestClass copy){
         this.list = new ArrayList<Integer>(copy.list);
         this.count = copy.count;
      }

      ...
 }

Then to use it : 然后使用它:

TestClass newObj= new TestClass(obj);

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

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