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.
1 |
public boolean isEmpty() |
The isEmpty
method returns a boolean value indicating whether there are any elements in the LinkedList (i.e. it is empty or not).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.LinkedList; public class CheckIfLinkedListIsEmptyExample { public static void main(String[] args) { //create new LinkedList object LinkedList<String> linkedListColors = new LinkedList<String>(); /* * Use the isEmpty method to check if the list * object is empty. * * It returns true if the list is empty, false otherwise. */ //this should return true as there are no elements in the LinkedList System.out.println( linkedListColors.isEmpty() ); //add an element linkedListColors.add("Yellow"); //this should return false as there is one element in the LinkedList System.out.println( linkedListColors.isEmpty() ); } } |
Output
1 2 |
true false |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.LinkedList; public class CheckIfLinkedListIsEmptyExample { public static void main(String[] args) { //create new LinkedList object LinkedList<String> linkedListColors = new LinkedList<String>(); //this should return true as there are no elements in the LinkedList System.out.println( "Is empty? " + (linkedListColors.size() == 0) ); //add an element linkedListColors.add("Yellow"); //this should return false as there is one element in the LinkedList System.out.println( "Is empty? " + (linkedListColors.size() == 0) ); } } |
Output
1 2 |
Is empty? true Is empty? false |
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.