Java addAll(集合)与 new ArrayList(集合)

标签 java collections arraylist

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

  1. Collection col2 = new ArrayList(col);

  2. 集合 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/

相关文章:

java - AtomicLong.lazySet 的 C++ 端口

java - 工厂方法和实用类之间有什么区别?

collections - 在tensorflow中,你可以定义自己的集合名称吗?

java - 按长属性对对象列表进行排序

java - 无法使用 JSTL 访问 bean

c# - 从非托管 C# DLL 返回列表/数组

java - Json Jackson 不反序列化内部对象(属性上为 null)

java - 柴笔 JAVA "AWT-EventQueue-0"java.lang.NumberFormatException : multiple points

java - 如何计算循环一次迭代的执行时间?

Java排序逻辑和识别两个对象的最大值