在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 ?
}
答案 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