clear() deletes every element from the collection and removeAll() one only removes the elements matching those from another Collection.
clear() method removes all of the elements from this list. The list will be empty after this call returns.
The Java ArrayList removeAll() method removes all the elements from the arraylist that are also present in the specified collection. The syntax of the removeAll() method is: arraylist. removeAll(Collection c); Here, arraylist is an object of the ArrayList class.
ArrayList clear() – Empty ArrayList in Java. ArrayList clear() method is used to removes all of the elements from the list.
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).
The time complexity of ArrayList.clear()
is O(n)
and of removeAll
is O(n^2)
.
So yes, ArrayList.clear
is much faster.
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.
Unless there is a specific optimization that checks if the argument passed to removeAll()
is the collection itself (and I highly doubt that such an optimization is there) it will be significantly slower than a simple .clear()
.
Apart from that (and at least equally important): arraylist.removeAll(arraylist)
is just obtuse, confusing code. It is a very backwards way of saying "clear this collection". What advantage would it have over the very understandable arraylist.clear()
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With