Assuming that arraylist
is defined as ArrayList
, is arraylist.removeAll(arraylist) equivalent to 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(n2) as opposed to clear
's O(n).
Array => once the space is allocated for an Array variable at the run time, the allocated space can not be extended or removed.
ArrayList => This is not the case in arraylist. ArrayList can grow and shrink at the run time. The allocated space can be minimized or maximized at the run time.
The clear()
method removes all the elements of a single ArrayList
. It's a fast operation, as it just sets the array elements to null
.
The removeAll(Collection)
method, which is inherited from AbstractCollection
, removes all the elements that are in the argument collection from the collection you call the method on. It's a relatively slow operation, as it has to search through one of the collections involved.
clear()
will go through the underlying Array and set each entry to null;
removeAll(collection)
will go through the ArrayList checking for collection and remove(Object)
it if it exists.
I would imagine that clear()
is way faster then removeAll because it's not comparing, etc.
Clear is faster because it does not loop over elements to delete. This method can assume that ALL elements can be deleted.
Remove all
does not necessarily mean delete all elements in the list, only those provided as parameters SHOULD be delete. Hence, more effort is required to keep those which should not be deleted.
CLARIFICATION
By 'loop', I mean it does not have to check whether the element should be kept or not. It can set the reference to null
without searching through the provided lists of elements to delete.
Clear
IS faster than deleteall
.
The time complexity of ArrayList.clear()
is O(n)
and of removeAll
is O(n^2)
.
So yes, ArrayList.clear
is much faster.