java - What is the difference between ArrayList.clear() and ArrayList.removeAll()?

ID : 10410

viewed : 24

Tags : javaarraylistjava

Top 5 Answer for java - What is the difference between ArrayList.clear() and ArrayList.removeAll()?

vote vote

98

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).

vote vote

81

The time complexity of ArrayList.clear() is O(n) and of removeAll is O(n^2).

So yes, ArrayList.clear is much faster.

vote vote

77

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.

vote vote

61

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()?

vote vote

56

They serve different purposes. clear() clears an instance of the class, removeAll() removes all the given objects and returns the state of the operation.

Top 3 video Explaining java - What is the difference between ArrayList.clear() and ArrayList.removeAll()?

Related QUESTION?