Check if an ArrayList is Empty in Java

Learn to check if ArrayList is empty or not using isEmpty() and size() methods. Please note that isEmpty() method also internally check the size of ArrayList.

1. Using ArrayList.isEmpty()

The ArrayList.isEmpty() method returns true if the list contains no elements. In other words, the method returns true if the list is empty. Else isEmpty() method returns false.

public boolean isEmpty();

In the given example, we first initialized an empty ArrayList and checked if it was empty. Method returns true because there is nothing inside the list.

ArrayList<String > list = new ArrayList();


Then we added an element "A" to list and check again. This time list is not empty, and the method returns false. Now we again cleared the list and checked again. The list is empty again.



In application programming, it is advisable to check both if list is not null and then not empty. If list is not initialized, we may get NullPointerException in runtime.

2. Using ArrayList.size()

Another way to check if the arraylist contains any element or not, we can check the size of the arraylist. If the list size is greater than zero, then the list is not empty. If the list size is 0, the list is empty.

If we look inside the isEmpty() method, it also checks the size of the arraylist to determine if it is empty.

ArrayList<String > list = new ArrayList();

Assertions.assertTrue(list.size() == 0);

Assertions.assertTrue(list.size() == 1);

Assertions.assertTrue(list.size() == 0);

Happy Learning !!

Read More: ArrayList Java Docs

Sourcecode on Github


Notify of
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.