Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a collection is empty in Java: which is the best method?

I have two ways of checking if a List is empty or not

if (CollectionUtils.isNotEmpty(listName))  

and

if (listName != null && listName.size() != 0) 

My arch tells me that the former is better than latter. But I think the latter is better.

Can anyone please clarify it?

like image 257
Vikrant Avatar asked Jun 22 '12 08:06

Vikrant


People also ask

How do you check if the collection is empty or not in Java?

The isEmpty() of java. util. Collection interface is used to check if the Collection upon which it is called is empty or not. This method does not take any parameter and does not returns any value.

How do you check if a set is null or not?

Set. isEmpty() method is used to check if a Set is empty or not. It returns True if the Set is empty otherwise it returns False.

How do I use CollectionUtils isEmpty?

isEmpty() method of CollectionUtils can be used to check if a list is empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list.

How do you check if an ArrayList is empty or null?

To check if an ArrayList is empty, you can use ArrayList. isEmpty() method or first check if the ArrayList is null, and if not null, check its size using ArrayList. size() method. The size of an empty ArrayList is zero.


1 Answers

You should absolutely use isEmpty(). Computing the size() of an arbitrary list could be expensive. Even validating whether it has any elements can be expensive, of course, but there's no optimization for size() which can't also make isEmpty() faster, whereas the reverse is not the case.

For example, suppose you had a linked list structure which didn't cache the size (whereas LinkedList<E> does). Then size() would become an O(N) operation, whereas isEmpty() would still be O(1).

Additionally of course, using isEmpty() states what you're actually interested in more clearly.

like image 178
Jon Skeet Avatar answered Oct 24 '22 23:10

Jon Skeet