Java ArrayList isEmpty() Method

Java ArrayList Java ArrayList

The isEmpty() method is used to determine whether the dynamic array is empty.

The syntax of the isEmpty() method is:

arraylist.isEmpty()

Note:arraylist is an object of the ArrayList class.

Parameter description:

  • None

Return Value

Returns true if there are no elements in the array.

Returns false if there are elements in the array.

Example

Check whether the dynamic array is empty:

Example

import java.util.ArrayList;

class Main {
    public static void main(String[] args){

        // Create a dynamic array
        ArrayList<String> sites = new ArrayList<>();
       
        // Check whether the array contains elements
        boolean result = sites.isEmpty(); // true
        System.out.println("Is sites empty? " + result);

        sites.add("Google");
        sites.add("Example");
        sites.add("Taobao");
        System.out.println("Website list: " + sites);

        // Check whether the array is empty
        result = sites.isEmpty();  // false
        System.out.println("Is sites empty? " + result);
    }
}

Executing the above program produces the following output:

sites 是否为空? true
网站列表: [Google, Example, Taobao]
sites 是否为空? false

In the example above, we created an array named sites, and the sites array uses the isEmpty() method to check whether the array contains elements.

Initially, the newly created array does not contain any elements. Therefore, isEmpty() returns true. Later, after we added some elements (Google, Example, etc.), the method returns false.

Java ArrayList Java ArrayList

Other extensions