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...
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 .
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.
isEmpty() method in Java is used to check if a list is empty. An empty list means that it contains no elements.
An empty collection is actually a collection, but there aren't any elements in it yet. null means no collection exists at all.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With