mar*_*pes 13 java collections arraylist
为什么我会得到不同的行为:
Collection col2 = new ArrayList(col);
Collection 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);
}
Run Code Online (Sandbox Code Playgroud)
Car*_*ter 16
此代码有效:
public void updateCollection(Collection<Object> col) {
this.objectCollection.clear();
this.objectCollection.addAll(col);
}
Run Code Online (Sandbox Code Playgroud)
但这引入了一些问题:
public void updateCollection(Collection<Object> col) {
this.objectCollection=new ArrayList(col);
}
Run Code Online (Sandbox Code Playgroud)
我怀疑你的第一种方法的这种变化会引入相同的问题:
public void updateCollection(Collection<Object> col) {
this.objectCollection = new ArrayList();
this.objectCollection.clear();
this.objectCollection.addAll(col);
}
Run Code Online (Sandbox Code Playgroud)
为什么?显然你在某处使用了另一个对objectCollection的引用.代码中的某个地方,另一个对象是(例如):
myCopyOfObjectCollection = theOtherObject.objectCollection;
如果您正在使用getter,这不会改变基础行为 - 您仍然会保留另一个参考.
因此,如果在初始分配时,例如,集合包含{1,2,3},您可以从以下开始:
当你为this.objectCollection 分配一个新的 ArrayList,并用,例如{4,5,6}填充它时,你得到这个:
"那个"仍然指向原始的ArrayList.
Collection col2 = new ArrayList(col);
Run Code Online (Sandbox Code Playgroud)
将创建一个新ArrayList的大小col.size()(+ 10%)并将所有元素复制col到该数组中.
Collection col2 = new ArrayList();
Run Code Online (Sandbox Code Playgroud)
将创建一个初始大小为10的新ArrayList(至少在Sun实现中).
col2.addAll(col);
Run Code Online (Sandbox Code Playgroud)
将所有元素复制col到最后col2 ArrayList,如果需要,扩大后备数组大小.
因此,根据您的col收藏大小,行为会有所不同,但不会太多.
最好使用第一个选项 - 这将避免至少一个额外的后备阵列扩展操作.
| 归档时间: |
|
| 查看次数: |
16753 次 |
| 最近记录: |