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

问题描述 投票:2回答:3

可能重复: 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 ?
}
java class object deep-copy
3个回答
4
投票

这不是一个深层复制 - 两个对象仍然引用相同的地图。

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


2
投票

x.a将引用与Multimap相同的y.a - 如果你添加/删除元素,它将被反映在两者中。

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

这是一个很深的副本。


1
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.