How to empty or clear ArrayList in Java

Learn to clear arraylist or empty an arraylist in Java. Clearing a list means to remove all elements from the list. It is same as reset the list to it’s initial state when it has no element stored in it.

To clear an arraylist in java, we can make use of two methods.

  1. ArrayList.clear()
  2. ArrayList.removeAll()

Both methods will finally empty the list. But there is a difference in how they perform the empty operation.

1. Clear arraylist with ArrayList.clear()

Java program to clear an arraylist.

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListExample 
{
    public static void main(String[] args) throws Exception 
    {
        ArrayList<String> list = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e"));
        
        System.out.println(list);
        
        list.clear();   //clear the list
        
        System.out.println(list);
    }
}

Program output.

[a, b, c, d, e]
[]

2. Clear arraylist with ArrayList.removeAll()

Java program to remove all elements of an arraylist with removeAll() method.

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListExample 
{
    public static void main(String[] args) throws Exception 
    {
        ArrayList<String> list = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e"));
        
        System.out.println(list);
        
        list.removeAll(list);   //remove all elements from self
        
        System.out.println(list);
    }
}

Program output.

[a, b, c, d, e]
[]

3. Difference between clear() vs removeAll() methods

As I said before, both methods empty an list. But difference lies in how they make list clear. Let’s see the code for both methods to understand the actions they perform.

  1. clear() method is simple. It iterates over list and assign null to each index in the list.
    public void clear() 
    {
        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;
    
        size = 0;
    }
    
  2. In removeAll() method, it first check if element is present or not using contains() method. If element is present then it is removed from the list. This happens for all the elements in the loop.
    public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }
    
    private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)
                    elementData[w++] = elementData[r];
        } finally {
            // Preserve behavioral compatibility with AbstractCollection,
            // even if c.contains() throws.
            if (r != size) {
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            if (w != size) {
                // clear to let GC do its work
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }
    

4. Conclusion

By going through the sourcecode of both methods, we can safely say that clear() method give much better performance because of less number of statements it executes.

removeAll() method lack in performance because of extra call to contains() method.

But, still removeAll() method is useful in cases such as merge two arraylists without duplicate elements.

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.