java new一个新集合_Java addAll(集合)與新的ArrayList(集合)

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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值