是什么ArrayList.clear()和ArrayList.removeAll()之间的区别? [英] What is the difference between ArrayList.clear() and ArrayList.removeAll()?
问题描述
假设的ArrayList
定义为的ArrayList<串GT;的ArrayList
是<一个href=\"http://developer.android.com/reference/java/util/AbstractCollection.html#removeAll%28java.util.Collection%3C?%3E%29\"><$c$c>arraylist.removeAll(arraylist)$c$c>相当于<一个href=\"http://developer.android.com/reference/java/util/ArrayList.html#clear%28%29\"><$c$c>arraylist.clear()$c$c>?
如果这样,我可以假设清()
方法是清空数组列表更有效率?
有没有在使用 arraylist.removeAll(数组列表)
而不是 arraylist.clear()
<?什么注意事项/ p>
来源$ C $ C为清()
:
公共无效明确(){
modCount的++; //让GC完成其工作
的for(int i = 0; I&LT;大小;我++)
elementData中[我] = NULL; 大小= 0;
}
源$ C $ C为的removeAll()
(如类AbstractCollection
定义):
公共布尔的removeAll(收集和LT;&GT; c){
布尔修改= FALSE;
迭代器&LT;&GT; E =迭代器();
而(e.hasNext()){
如果(c.contains(e.next())){
e.remove();
修改= TRUE;
}
}
返回修改;
}
清()
的速度要快得多,因为它没有处理所有这些额外的方法调用。
和作为Atrey指出, c.contains(..)
增加的removeAll
的时间复杂度到0 (N ^ 2),而不是明确
的O(N)。
Assuming that arraylist
is defined as ArrayList<String> arraylist
, is arraylist.removeAll(arraylist)
equivalent to arraylist.clear()
?
If so, can I assume that the clear()
method is more efficient for emptying the array list?
Are there any caveats in using arraylist.removeAll(arraylist)
instead of arraylist.clear()
?
The source code for clear()
:
public void clear() {
modCount++;
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
The source code for removeAll()
(As defined in AbstractCollection
):
public boolean removeAll(Collection<?> c) {
boolean modified = false;
Iterator<?> e = iterator();
while (e.hasNext()) {
if (c.contains(e.next())) {
e.remove();
modified = true;
}
}
return modified;
}
clear()
is much faster since it doesn't have to deal with all those extra method calls.
And as Atrey points out, c.contains(..)
increases the time complexity of removeAll
to O(n^2) as opposed to clear
's O(n).
这篇关于是什么ArrayList.clear()和ArrayList.removeAll()之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!