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

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 }

Another approach is to use Apache Commons Collections.

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

Tags:

Java

List