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...
4 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 } 0 Another approach is to use Apache Commons Collections.
Take a look in method CollectionUtils.isEmpty(). It is more concise.
1if (list == null) checking is list is null or not.
if (list.isEmpty()) checking is list is empty or not, If list is null and you call isEmpty() it will give you NullPointerException.
Its better to check whether list is null or not first and then check is empty or not.
if(list !=null && ! list.isEmpty()){ // do your code here
} 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