What is the ArrayList.isEmpty() method in Java?
The ArrayList.isEmpty() method in Java is used to check if a list is empty. An empty list means that it contains no elements.
Syntax
The ArrayList.isEmpty() method can be declared as shown in the code below:
public boolean isEmpty()
Return value
The ArrayList.isEmpty() method returns a boolean such that:
- The return value is
trueif the list is empty. - The return value is
falseif the list is not empty.
Example
Consider the code below, which demonstrates the use of the ArrayList.isEmpty() method:
import java.util.ArrayList;public class Example1 {public static void main(String[] args){ArrayList<Integer> list1 = new ArrayList<Integer>(5);boolean empty = list1.isEmpty();System.out.println("list1 is empty: " + empty);list1.add(1);list1.add(2);list1.add(3);empty = list1.isEmpty();System.out.println("list1 is empty: " + empty);}}
Explanation
- A list
list1is declared in line 6. - The
ArrayList.isEmpty()method is used in line 8 to check iflist1is empty. TheArrayList.isEmpty()returnstruebecauselist1contains no elements. - Three elements are added in
list1in lines 11-13 using theadd()method. - The
ArrayList.isEmpty()method is used in line 15 to check iflist1is empty. TheArrayList.isEmpty()returnsfalsebecauselist1now contains three elements.