ArrayList isEmpty() Method in Java

Published by user on

ArrayList isEmpty() checks if the list is empty or not. If returns true if the list is empty else false it returns false.

Syntax:

public boolean isEmpty()

This method doesn’t throw any exceptions.

Let’s try to understand this diagrammatically understand isEmpty() behavior.

arraylist isempty

Program to demonstrate ArrayList isEmpty()

Let’s have a look at the program.  After adding element the call to isEmpty() returns false. Once we clear() the list it returns true. The time complexity of this method is linear. If you still want to check that isEmpty is working correctly you can check if size() method returns 0.

import java.util.ArrayList;
import java.util.List;

public class ArrayListDemo1 {
	public static void main(String[] args) {
		List<Integer> numbers = new ArrayList<>();
		numbers.add(11);
		numbers.add(17);
		numbers.add(33);
		System.out.println("ArrayList element: " + numbers);
		System.out.println("Is the list empty: " + numbers.isEmpty());
		numbers.clear();
		System.out.println("ArrayList elements after clear(): " + numbers);
		System.out.println("Is the list empty: " + numbers.isEmpty());
	}
}

Output:

ArrayList element: [11, 17, 33]
Is the list empty: false
ArrayList elements after clear(): []
Is the list empty: true

That’s all for this article. Please share it if you find this helpful.

Further Reading:

ArrayList Reference Document

Categories: Java