Collections

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. Example also shows how to check if ArrayList is empty using size or isEmpty method.

How to check if ArrayList is empty in Java?

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

1) Check if ArrayList is empty using size method

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

This method returns number of elements contained in the ArrayList.

Output

2) Check if ArrayList is empty using isEmpty method

ArrayList class provides a method isEmpty just for this specific purpose, to check if ArrayList is empty or not.

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

Output

What is the preferred method to check if ArrayList is empty?

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

size method source code

isEmpty method source code

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

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

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

About the author

rahimv

rahimv

rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

Your email address will not be published. Required fields are marked *