26

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...

hc0re
  • 1,806
  • 2
  • 26
  • 61
  • 2
    Be careful if/when you change this - a list can be initialized and empty - but if you try list.isEmpty() on a null list - you'll get a NullPointerException. – Ofer Lando Jan 22 '15 at 12:53
  • 1
    *"But why use this construction when we have `list.isEmpty()` method..."* Because if you use `list.isEmpty()` on a `list` variable for which `list == null` is true, it'll throw a `NullPointerException`. The two checks are fundamentally, completely, different. – T.J. Crowder Jan 22 '15 at 12:54

4 Answers4

62

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 }
Eran
  • 387,369
  • 54
  • 702
  • 768
18

Another approach is to use Apache Commons Collections.

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

josivan
  • 1,963
  • 1
  • 15
  • 26
11

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

Saad Joudi
  • 595
  • 4
  • 5
3

if (list == null) checks whether the list is null or not.

if (list.isEmpty()) checks whether the list is empty or not. If the list is null and if you call isEmpty(), then it will give you a NullPointerException.

It's better to check whether the list is null or not first, and then check if it is empty or not.

if (list != null && !list.isEmpty()) {
    // do your code here
}
António Ribeiro
  • 4,129
  • 5
  • 32
  • 49
atish shimpi
  • 4,873
  • 2
  • 32
  • 50