Skip to content

Check If LinkedList is Empty in Java Example

This example shows how to check if the LinkedList is empty in Java using the isEmpty method as well as the size method of the LinkedList class.

How to check if the LinkedList object is empty in Java?

There are a couple of ways using which you can check if the LinkedList is empty in Java.

1. Using the isEmpty method

The isEmpty method of the LinkedList class returns true if the LinkedList object is empty.

The isEmpty method returns a boolean value indicating whether there are any elements in the LinkedList (i.e. it is empty or not).

Output

2. Using the size method

You can also do the same empty check using the size method of the LinkedList class. Get the size of the linked list and compare it with the 0 to check if the linked list is empty.

Output

What is the suggested way to check?

The isEmpty method internally uses the size to check if the list is empty or not. So performance-wise there is not much difference between these two methods.

However, the isEmpty method clearly tells the purpose of the code and is more readable than getting the size and comparing it with the 0. Hence, using the isEmpty method is the suggested way to check.

This example is a part of the LinkedList in Java tutorial.

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

About the author

Leave a Reply

Your email address will not be published.