ArrayList isEmpty() Method in Java with Examples (original) (raw)
Last Updated : 11 Dec, 2024
In Java, the **isEmpty() method of ArrayList is used to check if an ArrayList is empty.
**Example 1: Here, we use the **isEmpty() method **to check whether an ArrayList of integers is empty.
Java `
// Java program to demonstrate the use of isEmpty() // method with ArrayList of Integers import java.util.ArrayList;
public class GFG { public static void main(String[] args) {
// Creating an empty ArrayList of Integers
ArrayList<Integer> n = new ArrayList<>();
// Checking if the ArrayList is empty
boolean res = n.isEmpty();
System.out.println("" + res);
// Adding an element
// to the ArrayList
n.add(21);
// Checking again if the
// ArrayList is empty
res = n.isEmpty();
System.out.println("" + res);
}
}
`
Syntax of ArrayList isEmpty()
Method
public boolean isEmpty()
**Return Type: It returns a boolean value, true
if the list is empty, otherwise false
.
**Example 2: Here, we use the **isEmpty() method **to check if an ArrayList of **strings **is empty.
Java `
// Java program to demonstrate the use of // isEmpty() method with ArrayList of Strings import java.util.ArrayList;
public class GFG { public static void main(String[] args) {
// Creating an ArrayList of Strings
ArrayList<String> s = new ArrayList<>();
// Checking if the ArrayList is empty
System.out.println("" + s.isEmpty());
// Adding an element to
// the ArrayList
s.add("Cherry");
// Checking again if the
// ArrayList is empty
System.out.println("" + s.isEmpty());
}
}
`
**Example 3: Here, we will use the **isEmpty() method **to check if an ArrayList of Objects is empty.
Java `
// Java program to demonstrate the use of // isEmpty() method with custom Objects import java.util.ArrayList;
class Person { String n; int a;
// Constructor
public Person(String n, int a) {
this.n = n;
this.a = a;
}
}
public class Main { public static void main(String[] args) {
// create an ArrayList of Person objects
ArrayList<Person> p = new ArrayList<>();
// check if the ArrayList is empty
System.out.println("" + p.isEmpty());
// add a Person object to the ArrayList
p.add(new Person("Sweta", 24));
// check again if the ArrayList is empty
System.out.println("" + p.isEmpty());
}
}
`