问题描述
限时送ChatGPT账号..假设 arraylist
被定义为 ArrayList
,是 arraylist.removeAll(arraylist)
等价于 arraylist.clear()
?
Assuming that arraylist
is defined as ArrayList<String> arraylist
, is arraylist.removeAll(arraylist)
equivalent to arraylist.clear()
?
如果是这样,我可以假设 clear()
方法更有效地清空数组列表吗?
If so, can I assume that the clear()
method is more efficient for emptying the array list?
使用arraylist.removeAll(arraylist)
代替arraylist.clear()
有什么注意事项吗?
Are there any caveats in using arraylist.removeAll(arraylist)
instead of arraylist.clear()
?
推荐答案
clear()
的源码:
public void clear() {
modCount++;
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
removeAll()
的源代码(在AbstractCollection
中定义):
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()
快得多,因为它不必处理所有这些额外的方法调用.
clear()
is much faster since it doesn't have to deal with all those extra method calls.
正如 Atrey 指出的那样,c.contains(..)
将 removeAll
的时间复杂度增加到 O(n2) 作为与 clear
的 O(n) 相反.
And as Atrey points out, c.contains(..)
increases the time complexity of removeAll
to O(n2) as opposed to clear
's O(n).
这篇关于ArrayList.clear() 和 ArrayList.removeAll() 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论