Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two ways to check if a list is empty - differences?

Tags:

java

list

I have a short question.

Lets assume we have a List which is an ArrayList called list. We want to check if the list is empty.

What is the difference (if there is any) between:

if (list == null) { do something }

and

if (list.isEmpty()) { do something }

I'm working on an ancient code (written around 2007 by someone else) and it is using the list == null construction. But why use this construction when we have list.isEmpty() method...

like image 403
dziki Avatar asked Jan 22 '15 12:01

dziki


People also ask

How do you check a list is empty or not?

Using len() With Comparison Operator In the code above, len(py_list) == 0 will be true if the list is empty and will will be redirected to the else block. This also allows you to set other values as well, rather than relying on 0 being converted as False . All other positive values are converted to True .

How do I check if a list is empty in Python?

In this solution, we use the len() to check if a list is empty, this function returns the length of the argument passed. And given the length of an empty list is 0 it can be used to check if a list is empty in Python.

How do you check if a list is an empty list in Java?

isEmpty() method in Java is used to check if a list is empty. An empty list means that it contains no elements.

What is the difference between an empty list and a null list?

An empty collection is actually a collection, but there aren't any elements in it yet. null means no collection exists at all.


3 Answers

The first tells you whether the list variable has been assigned a List instance or not.

The second tells you if the List referenced by the list variable is empty. If list is null, the second line will throw a NullPointerException.

If you want to so something only when the list is empty, it is safer to write :

if (list != null && list.isEmpty()) { do something }

If you want to do something if the list is either null or empty, you can write :

if (list == null || list.isEmpty()) { do something }

If you want to do something if the list is not empty, you can write :

if (list != null && !list.isEmpty()) { do something }
like image 88
Eran Avatar answered Oct 17 '22 14:10

Eran


Another approach is to use Apache Commons Collections.

Take a look in method CollectionUtils.isEmpty(). It is more concise.

like image 18
josivan Avatar answered Oct 17 '22 12:10

josivan


For Spring developers, there's another way to check this with only one condition :

    !CollectionUtils.isEmpty(yourList)

This allow you to test if list !=null and !list.isEmpty()

PS : should import it from org.springframework.util.CollectionUtils

like image 6
Saad Joudi Avatar answered Oct 17 '22 13:10

Saad Joudi