Clear arraylist in java

In this article, we will understand how to clear an arraylist in java in 2 different ways with examples.
Clearing an arraylist means removing all its elements so that it becomes empty and its size becomes 0.

Method 1: Using clear() method
ArrayList clear() method removes all the elements of the list so that it becomes empty.
Java doc for clear() method states

Removes all of the elements from this list. The list will be empty after this call returns.

Program example of clear() method to clear arraylist is given below

// define arraylist
List<String> l = new ArrayList<>();
// add elements
l.add("A");
l.add("B");
l.add("C");
// print contents & size
System.out.println("List contents: " + l);
System.out.println("List size: " + l.size());
// clear arraylist
l.clear();
// print contents & size
System.out.println("List contents after clear: " + l);
System.out.println("List size after clear: " + l.size());

Below is the output

List contents: [A, B, C] List size: 3
List contents after clear: [] List size after clear: 0

clear() is declared in List interface and its implementation is written in ArrayList class as below

public void clear() {
  modCount++;
  final Object[] es = elementData;
  for (int to = size, i = size = 0; i < to; i++)
    es[i] = null;
  }
}

As you can see, clear() iterates over the underlying list array and sets each element to null. It also sets the size variable to 0, so that when you attempt to get the length of the list using size() method, it returns 0.

clear() throws UnsupportedOperationException, if is invoked on a list that does not support this method. Example,

List<String> l = List.of("A","B","C"); 
l.clear();

In this case invoking clear() will raise java.lang.UnsupportedOperationException since List.of() returns an immutable list.

Method 2: Using removeAll()
An arraylist can be cleared using its removeAll() method.
removeAll() accepts a collection as argument. It is invoked on a list object and removes all elements from the list which are also present in the argument collection.
So, to clear a list, we need to pass the same list as argument to removeAll().

Java doc for removeAll() states,

Removes from this list all of its elements that are contained in the specified collection

Example of removeAll() method to clear an arraylist is given below

// define arraylist
List<String> l = new ArrayList<>();
l.add("A");
l.add("B");
l.add("C");
// print contents & size
System.out.println("List contents: " + l);
System.out.println("List size: " + l.size());
// clear arraylist
l.removeAll(l);
// print contents & size
System.out.println("List contents after clear: " + l);
System.out.println("List size after clear: " + l.size());

Output is

List contents: [A, B, C] List size: 3
List contents after clear: [] List size after clear: 0

removeAll() removes all elements from the argument collection which match the elements in the list on which it is called.
So, if the invoking list and argument list are same, then it will remove all the elements from arraylist.

removeAll() will throw

    • NullPointerException, if the list contains a null element while the argument collection does not allow null elements, such as in below example
      List<String> l = new ArrayList<>();
      l.add("A");
      l.add("B");
      l.add(null);
      l.add("E");
      l.removeAll(List.of("B", "D"));

      This is because list created using List.of() does not allow null elements.

    • ClassCastException, if the list contains an element which is incompatible with the type of argument collection.
      This is because removeAll() compares the elements of both the collections and while comparison, if the types of both elements are different, then ClassCastException is raised.

ArrayList clear() vs removeAll()
Following are important differences between ArrayList clear() and removeAll() methods.

  1. Syntax
    First difference between clear() and removeAll() is the syntax in which they are invoked.
    While clear() is directly invoked in the list object, removeAll() requires that the list is also supplied as an argument.
  2. Purpose
    clear() has a single purpose of removing all elements from a list while removeAll() can also be used to remove list elements which are not present in some other collection.
  3. Algorithm
    clear() method simply iterates over the list and sets each element to null and size variable of ArrayList to 0.
    removeAll() compares the elements of the collection argument with the list elements using contains() and sets matching elements to null.
  4. Complexity
    There is only a single loop in clear(). So the time complexity of this method is O(n).If you look at the source code of removeAll(), there are 3 loops.
    Out of these,
    A. One is a conditional loop, which breaks as soon as it finds the first mismatching element between the list and the argument collection.
    B. Second loop replaces the elements in the list which are present in the argument collection with list elements only, there by adding duplicate elements to the list.
    All duplicate elements are placed at the end of the list.
    For comparing the elements of collection and list, it uses contains(), which further has more loops
    C. Third loop sets the duplicate list elements created in second step to null.
    These steps might seem confusing. For better understanding, go through the source code of replaceAll().
    Considering all the above steps, the complexity of replaceAll() comes out to be O(n2).

Thus, considering all these comparisons, clear() method is more suitable to remove all elements from a list.

To conclude, there are two ways to clear an ArrayList using clear() and removeAll() methods.