The isEmpty() method of java.util.ArrayList class is used to check whether the list is empty or not. This method returns a boolean value. It returns true if the list is empty, and false if the list contains any elements.
Syntax
public boolean isEmpty()
Example
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
// Create an empty ArrayList
ArrayList<String> list = new ArrayList<>();
// Check if the list is empty or not using isEmpty()
boolean isEmptyInitially = list.isEmpty();
System.out.println("Is the list empty initially? " + isEmptyInitially);
// Add an element to the list
list.add("Hello");
// Check if the list is empty after adding an element
boolean isEmptyAfterAdd = list.isEmpty();
System.out.println("Is the list empty after adding an element? " + isEmptyAfterAdd);
// Clear the list (Removing all elements)
list.clear();
// Check if the list is empty after clearing
boolean isEmptyAfterClear = list.isEmpty();
System.out.println("Is the list empty after clearing? " + isEmptyAfterClear);
}
}
Output:
Is the list empty initially? true
Is the list empty after adding an element? false
Is the list empty after clearing? true
Explanation
- Initialization: An
ArrayListis created. - Initial Check: We check whether the list is empty using
isEmpty()method, since the list is not yet initialized, it returns true. - Adding Element: We then add an element
"Hello"to the list. - Check After Adding: We again check the list using
isEmpty()method, this time it returns false as the list contains an element. - Clearing the List: We delete all the elements of the list using
clear()method. - Check After Clearing: We again check the list, this time it returns true as the list is empty.
Leave a Reply