本文介绍了Java addAll(collection)vs new ArrayList(collection)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我得到不同的行为:

Why do i get different behaviors with:


  1. 集合col2 = new ArrayList ;

集合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);
}


推荐答案

p>

This code works:

public void updateCollection(Collection<Object> col) {
    this.objectCollection.clear();
    this.objectCollection.addAll(col);
}

但这会带来一些问题:

public void updateCollection(Collection<Object> col) {
    this.objectCollection=new ArrayList(col);
}

我怀疑你的第一个方法的这个变化会引入相同的问题: p>

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;

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}

ArrayList to 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}

that仍指向原始的ArrayList。

"that" is still pointing to the original ArrayList.

这篇关于Java addAll(collection)vs new ArrayList(collection)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 02:55