Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

arraylist

People also ask

What is the difference between removeAll () and clear () method in list Inter face?

clear() deletes every element from the collection and removeAll() one only removes the elements matching those from another Collection.

What does ArrayList clear do?

clear() method removes all of the elements from this list. The list will be empty after this call returns.

What is removeAll method?

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.

Can you clear an empty ArrayList in Java?

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