问题描述
为什么我会出现不同的行为:
Why do i get different behaviors with:
Collection col2 = new ArrayList(col);
Collection col2 = new ArrayList();
col2.addAll(col)
我正在与观众一起工作,代码很复杂,我试图解释问题的根源".另一个有趣的事实是下一个......
I'm working with viewers, and the code is complex, and i'm trying to explain the "root" of the problem. Another interesting fact is the next one...
//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);
}
我怀疑您的第一种方法的这种变化会引入相同的问题:
I suspect that this variation on your first method would introduce identical problems:
public void updateCollection(Collection<Object> col) {
this.objectCollection = new ArrayList();
this.objectCollection.clear();
this.objectCollection.addAll(col);
}
为什么?显然,您在某处使用了另一个对 objectCollection
的引用.在您的代码中,另一个对象说(例如):
Why? Evidently you have another reference to objectCollection
in use somewhere. Somewhere in your code, another object is saying (for instance):
myCopyOfObjectCollection = theOtherObject.objectCollection;
如果您正在使用 getter,那不会改变基本行为 - 您仍然保留另一个 引用.
If you're using a getter, that doesn't change the underlying behavior - you are still keeping another reference around.
因此,如果在初始分配中,例如,集合包含 {1, 2, 3},则开始时:
So if on initial assignment, say, the collection contained {1, 2, 3}, you start out with:
this.objectCollection
: {1, 2, 3}that.copyOfObjectCollection
:{1, 2, 3}
this.objectCollection
: {1, 2, 3}that.copyOfObjectCollection
: {1, 2, 3}
当您将 new ArrayList 分配给 this.objectCollection
,并使用 {4, 5, 6} 填充它时,您会得到:
When you assign a new ArrayList to this.objectCollection
, and populate it with, say, {4, 5, 6}, you get this:
this.objectCollection
: {4, 5, 6}that.copyOfObjectCollection
:{1, 2, 3}
this.objectCollection
: {4, 5, 6}that.copyOfObjectCollection
: {1, 2, 3}
所以 that
仍然指向原始的 ArrayList.
So that
is still pointing to the original ArrayList.
这篇关于Java addAll(collection) vs new ArrayList(collection)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!