Skip to content

Java ArrayList empty clear example

Java ArrayList empty clear example shows how to empty ArrayList in Java. The 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) Using the clear method

To empty ArrayList or remove all elements of ArrayList, you can use the clear method of the 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) Using the removeAll method

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

Output

3) Using the ArrayList constructor

Another alternative to emptying an ArrayList is to create a new ArrayList object and assign it to the 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? Well, the answer depends on the requirement.

By looking at the source code, the clear method sets all elements of ArrayList to null. While the removeAll method gets the Iterator, loops through the list using it and removes elements by checking if the list contains the element first. So the clear method is much faster than the removeAll method and is the recommended way to empty the 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, for example, 10000 elements to ArrayList, the internal array which backs the ArrayList is grown to accommodate 10000 elements.

When you empty the ArrayList using the clear method, it retains the capacity to hold 10000 elements. If you are going to add roughly the same number of elements, the clear method is the 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 a new ArrayList object.

This example is a part of the Java ArrayList tutorial with examples.

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

About the author

Leave a Reply

Your email address will not be published.