如何在java中深层复制对象?

时间:2011-03-29 23:07:46

标签: java class object deep-copy

  

可能重复:
  How do I copy an object in Java?

在java中这样做是否可以?

public class CacheTree {

    private Multimap<Integer, Integer> a;
    private Integer                    b;

        public void copy(CacheTree anotherObj) {
            this.a = anotherObj.getA();
            this.b = anotherObj.getB();
        }

       public Multimap<Integer, Integer> getA() {
            return a;
       }

       public Integer getB() {
            return b;
       }
}

public void main() {
     CacheTree x = new CacheTree();
     CacheTree y = new CacheTree();

     x.copy(y);      // Is it ok ?
}

3 个答案:

答案 0 :(得分:4)

这不是副本 - 两个对象仍然引用相同的地图。

您需要显式创建新的MultiMap实例并复制原始实例中的内容。

答案 1 :(得分:2)

x.a会引用与Multimap相同的y.a - 如果您添加/删除元素,则会在两者中反映出来。

this.a = new Multimap<Integer, Integer>();
this.a.addAll(anotherObj.getA())

这是一份很深的副本。

答案 2 :(得分:1)

参见这篇文章,给出了第2页中代码的一个很好的例子。 它还解释了java中深度复制的概念

http://www.javaworld.com/javaworld/javatips/jw-javatip76.html

相关问题