在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 ?
}
这不是一个深层复制 - 两个对象仍然引用相同的地图。
您需要显式创建一个新的MultiMap
实例并复制原始实例中的内容。
x.a
将引用与Multimap
相同的y.a
- 如果你添加/删除元素,它将被反映在两者中。
this.a = new Multimap<Integer, Integer>();
this.a.addAll(anotherObj.getA())
这是一个很深的副本。
看到这篇文章,给出了第2页中代码的一个很好的例子。它还解释了java中深度复制的概念
http://www.javaworld.com/javaworld/javatips/jw-javatip76.html