Assuming that arraylist is defined as ArrayList 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).

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐