HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions

How to empty or clear ArrayList in Java

By Lokesh Gupta | Filed Under: Java ArrayList

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

About Lokesh Gupta

Founded HowToDoInJava.com in late 2012. I love computers, programming and solving problems everyday. A family guy with fun loving nature. You can find me on Facebook, Twitter and Google Plus.

Ask Questions & Share Feedback Cancel reply

Your email address will not be published. Required fields are marked *

*Want to Post Code Snippets or XML content? Please use [java] ... [/java] tags otherwise code may not appear partially or even fully. e.g.
[java] 
public static void main (String[] args) {
...
}
[/java]

Search Tutorials

  • Email
  • Facebook
  • RSS
  • Twitter

ArrayList Methods

  • ArrayList – add()
  • ArrayList – addAll()
  • ArrayList – clear()
  • ArrayList – clone()
  • ArrayList – contains()
  • ArrayList – ensureCapacity()
  • ArrayList – forEach()
  • ArrayList – get()
  • Arraylist – indexOf()
  • Arraylist – lastIndexOf()
  • ArrayList – listIterator()
  • ArrayList – remove()
  • ArrayList – removeAll()
  • ArrayList – removeIf()
  • ArrayList – retainAll()
  • ArrayList – sort()
  • ArrayList – spliterator()
  • ArrayList – subList()
  • ArrayList – toArray()

ArrayList Examples

  • ArrayList – Initialize arraylist
  • ArrayList – Iteration
  • ArrayList – Add/replace element
  • ArrayList – Add multiple elements
  • ArrayList – Check empty list
  • ArrayList – Remove element
  • ArrayList – Replace element
  • ArrayList – Empty arraylist
  • ArrayList – Synchronized arraylist
  • ArrayList – Compare two lists
  • ArrayList – Remove duplicates
  • ArrayList – Merge two lists
  • ArrayList – Serialization
  • ArrayList – Swap two elements
  • Convert ArrayList to Array
  • Convert Array to ArrayList
  • Convert HashSet to ArrayList
  • Convert LinkedList to ArrayList
  • Convert Vector to ArrayList
  • ArrayList vs LinkedList
  • ArrayList vs Vector

Java Collections

  • Collections Framework
  • Array
  • ArrayList
  • LinkedList
  • HashMap
  • Hashtable
  • LinkedHashMap
  • TreeMap
  • HashSet
  • LinkedHashSet
  • TreeSet
  • Comparable
  • Comparator
  • Iterator
  • ListIterator
  • Spliterator
  • PriorityQueue
  • PriorityBlockingQueue
  • ArrayBlockingQueue
  • LinkedTransferQueue
  • CopyOnWriteArrayList
  • CopyOnWriteArraySet
  • Collection Sorting
  • Interview Questions

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Java Collections
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap