为什么我会得到不同的行为:
Collection col2 = new ArrayList(col);
集合 col2 = new ArrayList();
col2.addAll(col)
我正在与观众合作,代码很复杂,我正试图解释问题的“根源”。另一个有趣的事实是下一个......
//IF i use this code i have the correct behavior in my app:
public void updateCollection(Collection<Object> col) {
this.objectCollection.clear();
this.objectCollection.addAll(col);
}
//IF i use this code i have unexpected behavior in my app:
public void updateCollection(Collection<Object> col) {
this.objectCollection=new ArrayList(col);
}
最佳答案
此代码有效:
public void updateCollection(Collection<Object> col) {
this.objectCollection.clear();
this.objectCollection.addAll(col);
}
但这会带来问题:
public void updateCollection(Collection<Object> col) {
this.objectCollection = new ArrayList(col);
}
我怀疑您第一种方法的这种变体会引入相同的问题:
public void updateCollection(Collection<Object> col) {
this.objectCollection = new ArrayList();
this.objectCollection.clear();
this.objectCollection.addAll(col);
}
为什么?显然,您在某处使用了对 objectCollection
的另一个引用。在您的代码中的某处,另一个对象在说(例如):
myCopyOfObjectCollection = theOtherObject.objectCollection;
如果您使用的是 getter,那不会改变底层行为 - 您仍然保留着另一个 reference。
因此,如果在初始分配时,比方说集合包含 {1, 2, 3},您从:
this.objectCollection
:{1, 2, 3}that.copyOfObjectCollection
:{1, 2, 3}
当您将一个新的 ArrayList 分配给this.objectCollection
,并用例如{4, 5, 6} 填充它时,您会得到:
this.objectCollection
:{4, 5, 6}that.copyOfObjectCollection
:{1, 2, 3}
所以 that
仍然指向原始的 ArrayList。
关于Java addAll(集合)与 new ArrayList(集合),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4238654/