sách gpt4 ai đã đi

Java addAll(Collection) so với new ArrayList(Collection)

In lại 作者:搜寻专家 更新时间:2023-10-30 21:03:06 27 4
mua khóa gpt4 Nike

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

  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 col) {
this.objectCollection.clear();
this.objectCollection.addAll(col);
}

//IF i use this code i have unexpected behavior in my app:
public void updateCollection(Collection col) {
this.objectCollection=new ArrayList(col);
}

1 Câu trả lời

此代码有效:

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

但这会带来问题:

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

我怀疑您第一种方法的这种变体会引入相同的问题:

public void updateCollection(Collection 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}

当您将一个Mới ArrayList 分配给this.objectCollection,并用例如{4, 5, 6} 填充它时,您会得到:

  • this.objectCollection:{4, 5, 6}
  • that.copyOfObjectCollection:{1, 2, 3}

Vì thế that 仍然指向原始的 ArrayList。

关于Java addAll(集合)与 new ArrayList(集合),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4238654/

27 4 0
Bài viết được đề xuất: java - Java物理机呢?
Bài viết được đề xuất: javascript - 正则表达式的对象可能是 'null'
Bài viết được đề xuất: typescript - 映射类型的交集
Bài viết được đề xuất: java - "Turn off"输出流
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com