1. Using ArrayList class isEmpty() method
2. Using ArrayList class size() method
Read Also: ArrayList add(index, element) method example
Let's dive deep into the topic:
Check if an ArrayList is empty or not in Java
1. Using isEmpty() method of ArrayList class
ArrayList class isEmpty() method internally check the size() method of ArrayList. According to Oracle docs, the isEmpty() method returns true if the list contains no elements, otherwise, it returns false. The syntax of the isEmpty() method is given below:
public boolean isEmpty()
In the below example, initially, we will create an ArrayList and add no elements to it. Then we will check whether ArrayList is empty or not using the isEmpty() method. After that, we added two elements "Java" and "Python" to the ArrayList and checked again. This time ArrayList is not empty as it contains two elements. isEmpty() method will return false. The last step is to call the clear() method on the ArrayList. It will clear the ArrayList. Now, the isEmpty() method will return true again.
import java.util.*;
public class ArrayListisEmptyExample {
public static void main(String args[]) {
ArrayList<String> al = new ArrayList<>();
System.out.println("Is ArrayList empty? " + al.isEmpty());
al.add("Java");
al.add("Python");
System.out.println("Is ArrayList empty after adding elements? " + al.isEmpty());
al.clear();
System.out.println("Is ArrayList empty after clearing elements? " + al.isEmpty());
}
}
Output:
Is ArrayList empty? true
Is ArrayList empty after adding elements? false
Is ArrayList empty after clearing elements? true
2. Using size() method of ArrayList class
We can easily check if an ArrayList is empty or not in Java using the ArrayList.size() method. If the size is greater than 0 then the ArrayList is not empty otherwise if the size is 0 then it is empty. The syntax of the size() method is given below: public int size()
Given below is the complete example of ArrayList.size() method. If the size() returns 0, it means ArrayList is empty. Otherwise, ArrayList is not empty.
import java.util.*;
public class ArrayListisEmptyExample2 {
public static void main(String args[]) {
ArrayList<String> al2 = new ArrayList<>();
System.out.println("Is ArrayList empty? " + al2.size());
al2.add("C");
al2.add("C++");
System.out.println("Is ArrayList empty after adding elements? " + al2.size());
al2.clear();
System.out.println("Is ArrayList empty after clearing elements? " + al2.size());
}
}
Output:
Is ArrayList empty? 0
Is ArrayList empty after adding elements? 2
Is ArrayList empty after clearing elements? 0
That's all for today. Please mention in the comments if you have any questions related to how to check if an ArrayList is empty or not in Java.