Java LinkedList Clear, Empty, Remove All elements Example

This example shows how to clear LinkedList in Java (empty or remove all elements). This example also shows different ways to remove all elements from the Java LinkedList.

How to clear LinkedList in Java?

There are several ways using which we can empty the LinkedList in Java.

1. Using the clear method

The clear method of the LinkedList class removes all elements from the LinkedList.

The LinkedList becomes empty after this method call.

Output

2. Using the removeAll method

You can also use the removeAll method of the LinkedList class to remove all elements from the LinkedList.

The removeAll method is inherited from the AbstractCollection class.

Output

3. Using the remove method of the Iterator

We can remove all the elements of the list while iterating it using the remove method of the Iterator as given below.

Output

4. By assigning a new object to the reference

You can simply reassign a new empty linked list object to the existing reference as given below.

Output

Which method should I use to clear the LinkedList?

The first three approaches iterate the linked list in order to remove all the elements from it. While this is ok for the list having a small number of elements, but it can affect the performance if the number of elements contained in the linked list is very large.

The fourth approach reassigns the existing reference to a new empty linked list object. It involves a costly object creation operation and leaves the other work to be done by the garbage collection thread instead of the main thread.

This example is a part of the Java LinkedList tutorial.

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

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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