15
This code works:
這段代碼:
public void updateCollection(Collection col) {
this.objectCollection.clear();
this.objectCollection.addAll(col);
}
But this introduces problems:
但這介紹問題:
public void updateCollection(Collection col) {
this.objectCollection=new ArrayList(col);
}
I suspect that this variation on your first method would introduce identical problems:
我懷疑你的第一個方法的這種變化會帶來相同的問題:
public void updateCollection(Collection col) {
this.objectCollection = new ArrayList();
this.objectCollection.clear();
this.objectCollection.addAll(col);
}
Why? Evidently you have another reference to objectCollection in use somewhere. Somewhere in your code, another object is saying (for instance):
為什么?顯然,您在某些地方使用了objectCollection的另一個引用。在代碼中的某個地方,另一個對象正在說(例如):
myCopyOfObjectCollection = theOtherObject.objectCollection;
myCopyOfObjectCollection = theOtherObject.objectCollection;
If you're using a getter, that doesn't change the underlying behavior - you are still keeping another reference around.
如果您正在使用一個getter,這不會改變底層的行為——您仍然保留着另一個引用。
So if on initial assignment, say, the collection contained {1, 2, 3}, you start out with:
因此,如果在初始賦值時,比如集合包含{1,2,3},則從:
this.objectCollection : {1, 2, 3}
這一點。objectCollection: {1,2,3}
that.copyOfObjectCollection: {1, 2, 3}
那copyOfObjectCollection:{ 1,2,3 }
When you assign a new ArrayList to this.objectCollection, and populate it with, say, {4, 5, 6}, you get this:
當你給它分配一個新的ArrayList時。objectCollection,並使用{4,5,6}填充它,您將得到:
this.objectCollection : {4, 5, 6}
這一點。objectCollection: {4,5,6}
that.copyOfObjectCollection: {1, 2, 3}
那copyOfObjectCollection:{ 1,2,3 }
"that" is still pointing to the original ArrayList.
“that”仍然指向原始的ArrayList。