ArrayList clear() Method – How to Empty or clear ArrayList in Java

In this article, we will look at the ArrayList clear() method to remove all the elements from the list

1. ArrayList clear() method Syntax

Before we look in to more details, let’s look at the clear() method syntax from the ArrayList.The ArrayList clear() method will iterate through each element of the list and just sets the array elements to null.

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

If we just want to clear the ArrayList, clear() method will much faster as it only set the reference to each element as null doing no additional data manipulation.

How to empty and ArrayList in Java?

We can use ArrayList.clear() or ArrayList.removeAll() method to empty an ArrayList. The clear() method is the fastest as it only set the reference to the underlying array as null while the removeAll() will perform some additional work.

1. ArrayList clear() method Example

Here is a complete example to clear all the elements from an ArrayList.

package com.javadevjournal;

import java.util.ArrayList;
import java.util.List;


public class ArraylistClearExample {
    public static void main(String[] args) {

        List < String > list = new ArrayList < > ();
        list.add("Sunday");
        list.add("Monday");
        list.add("Tuesday");
        list.add("Wednesday");
        list.add("Thursday");
        list.add("Friday");
        list.add("Saturday");

        System.out.println(list);

        //clear the list
        list.clear();
        System.out.println(list);
    }
}

Output

[Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]
[]

When performing ArrayList.clear() it only removes references to array elements and sets size to 0, however, capacity stays as it was.

2. ArrayList.clear() or Create a New List?

When working on the ArrayList clear() method, there is a natural question “Should we use clear() method or create a new list using new ArrayList()?”. There are multiple reason we should prefer to use clear() method over new list.

  • Most times we might not be allowed to reassign a reference field that points to an ArrayList.
  • The variable might be declared as List. The actual type could be LinkedList and you want to preserve it instead of replacing the implementation with an ArrayList.
class App {
 // Can clear() but not reassign
 final List < String > list = new ArrayList < > ();
}

Keep in mind that it might be faster if the ArrayList will be cleared and refilled thousand times repeatedly as the clear() method will only clear the elements from the list but won’t change the size of backing array, this can definitely help us avoid dynamic resizing of the ArrayList.

3. ArrayList.clean() vs ArrayList.removeAll()

Both ArrayList.clear() and ArrayList.removeAll() empty an ArrayList, however they clear the list differently. Let’s look at the difference between the ArrayList.clear() vs ArrayList.removeAll().

  • The clear() method clear the list by assigning the null value to each element. It does not change the underlying backing Array.
 public void clear() {
   modCount++;
   final Object[] es = elementData;
   for (int to = size, i = size = 0; i < to; i++)
      es[i] = null;
 }
  • In removeAll() method, it first check if the element is present using the contains() method, it removes the element in case the item is present. The removeAll() perform some additional steps before removing an element from the underlying list.
public boolean removeAll(Collection << ? > c) {
    Objects.requireNonNull(c);
    boolean modified = false;
    Iterator << ? > it = iterator();
    while (it.hasNext()) {
        if (c.contains(it.next())) {
            it.remove();
            modified = true;
        }
    }
    return modified;
}
From ArrayList
public boolean removeAll(Collection << ? > c) {
    return batchRemove(c, false, 0, size);
}

boolean batchRemove(Collection << ? > c, boolean complement,
    final int from, final int end) {
    Objects.requireNonNull(c);
    final Object[] es = elementData;
    int r;
    // Optimize for initial run of survivors
    for (r = from;; r++) {
        if (r == end)
            return false;
        if (c.contains(es[r]) != complement)
            break;
    }
    int w = r++;
    try {
        for (Object e; r < end; r++)
            if (c.contains(e = es[r]) == complement)
                es[w++] = e;
    } catch (Throwable ex) {
        // Preserve behavioral compatibility with AbstractCollection,
        // even if c.contains() throws.
        System.arraycopy(es, r, es, w, end - r);
        w += end - r;
        throw ex;
    } finally {
        modCount += end - w;
        shiftTailOverGap(es, w, end);
    }
    return true;
}

Let’s look at some of the extra points while using these options:

  1. The clear() method on avg is much faster since it doesn’t have to deal with all those extra method calls as used in the removeAll() method.
  2. The c.contains() increase the time complexity of removeAll() method. (<strong>O(n)</strong> vs O(n<sup>2</sup>) )

Summary

In this article, we look at the ArrayList clear() method. We saw when we should use the clear() method as compare to creating and assigning a new ArrayList. At the end of this article, we look at the difference between the ArrayList clear() vs removeAll() method. The source code for these articles is available on our GitHub repository.