Collections

Java ArrayList empty clear example

Java ArrayList empty clear example shows how to empty ArrayList in Java. Example also shows how to remove all elements from ArrayList in Java.

How to empty ArrayList in Java?

There are several ways using which you can empty or clear ArrayList as given below.

1) Empty ArrayList using clear method

To empty ArrayList or remove all elements of ArrayList, you can use clear method of ArrayList class.

This method removes all elements from the ArrayList. ArrayList will be empty after this call and any new element you will add to the ArrayList will be added at index 0.

Output

2) Empty ArrayList using removeAll method

You can use removeAll method of Collections class to empty the ArrayList as given below.

Output

3) Empty ArrayList using ArrayList constructor

Another alternative to emptying an ArrayList is to create new ArrayList object and assign it to ArrayList reference as given below.

Output

What is the best way to empty ArrayList in Java?

As we have seen, there are multiple ways to empty the ArrayList. But what is the best method to empty it? Well, answer depends on the requirement.

By looking at the source code, clear method sets all elements of ArrayList to null. While removeAll method gets the Iterator, loops through the list using it and remove elements by checking if the list contains the element first. So clear method is much faster than removeAll method and is recommended way to empty ArrayList.

Point to remember is, as you add elements to ArrayList, its size or capacity grows. When you clear the ArrayList, all the elements are set to null, but the capacity remains as is. So if you have added, say for example, 10000 elements to ArrayList, the array which backs the ArrayList is grown to accommodate 10000 elements.

When you empty the ArrayList using clear method, it retains the capacity to hold 10000 elements. If you are going to add roughly the same number of elements, clear method is way to go as it does not have to resize the backing array when you add elements to it.

If that is not the case, you can just set the ArrayList reference to new ArrayList object.

Please let us know your views in the comments section below.

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.