Skip to content

Check if ArrayList is empty example in Java

Check if ArrayList is empty example in Java shows how to check if ArrayList is empty or not using the size or isEmpty method.

How to check if ArrayList is empty in Java?

There are a couple of ways to check if the ArrayList is empty as given below.

1) Using the size method

You can use the size method of the ArrayList class to check if the ArrayList is empty. If the ArrayList size is equal to 0 then the ArrayList is empty, otherwise not.

This method returns the number of elements contained in the ArrayList.

Output

2) Using the isEmpty method

The ArrayList class provides the isEmpty method just for this specific purpose.

This method returns true if the ArrayList does not contain any elements, false otherwise.

Output

What is the preferred method to check?

Let’s look at the source code of both of these methods.

size method source code

isEmpty method source code

Both of the methods rely on the size member variable. So in terms of the performance both the methods, i.e. size and isEmpty, are moreover the same. Using the isEmpty is recommended method because it clearly tells the purpose of the statement and it produces cleaner and easier to understand code too.

This example is a part of the ArrayList in Java tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.