AbstractCollection isEmpty() Method in Java with Examples
The isEmpty()
method is a part of the AbstractCollection
class in Java. It is used to check whether the collection is empty or not. The method returns true
if the collection is empty, otherwise, it returns false
.
Syntax:
public boolean isEmpty()
Example 1:
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
System.out.println("Is the list empty? " + list.isEmpty());
list.add("Java");
System.out.println("Is the list empty? " + list.isEmpty());
}
}
Output:
Is the list empty? true
Is the list empty? false
In the above example, we have created an ArrayList
and checked whether it is empty or not using the isEmpty()
method. Initially, the list is empty, so the method returns true
. After adding an element to the list, the method returns false
.
Example 2:
import java.util.HashSet;
public class Example {
public static void main(String[] args) {
HashSet<Integer> set = new HashSet<Integer>();
System.out.println("Is the set empty? " + set.isEmpty());
set.add(10);
System.out.println("Is the set empty? " + set.isEmpty());
}
}
Output:
Is the set empty? true
Is the set empty? false
In the above example, we have created a HashSet
and checked whether it is empty or not using the isEmpty()
method. Initially, the set is empty, so the method returns true
. After adding an element to the set, the method returns false
.
Example 3:
import java.util.LinkedList;
public class Example {
public static void main(String[] args) {
LinkedList<Double> list = new LinkedList<Double>();
System.out.println("Is the list empty? " + list.isEmpty());
list.add(3.14);
System.out.println("Is the list empty? " + list.isEmpty());
list.remove();
System.out.println("Is the list empty? " + list.isEmpty());
}
}
Output:
Is the list empty? true
Is the list empty? false
Is the list empty? true
In the above example, we have created a LinkedList
and checked whether it is empty or not using the isEmpty()
method. Initially, the list is empty, so the method returns true
. After adding an element to the list, the method returns false
. After removing the element from the list, the method again returns true
.