155

Does java.util.List.isEmpty() check if the list itself is null, or do I have to do this check myself?

For example:

List<String> test = null;

if (!test.isEmpty()) {
    for (String o : test) {
        // do stuff here            
    }
}

Will this throw a NullPointerException because test is null?

Lii
  • 11,553
  • 8
  • 64
  • 88
K''
  • 5,020
  • 7
  • 33
  • 43
  • It can't. An NPE would be thrown before it could be invoked. – user207421 Jan 04 '15 at 02:58
  • 1
    This ("Will this throw a NullPointerException because test is null?") is actually a very wrongly formulated question. You can easily test this question via a very simple test. The question itself of course takes to considering deeper insight into how the references in Java work, why is Java designed so this is not possible, but then you should have asked differently. – Honza Zidek Mar 04 '16 at 11:39

8 Answers8

160

You're trying to call the isEmpty() method on a null reference (as List test = null;). This will surely throw a NullPointerException. You should do if(test!=null) instead (checking for null first).

The method isEmpty() returns true, if an ArrayList object contains no elements; false otherwise (for that the List must first be instantiated that is in your case is null).

You may want to see this question.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Lion
  • 18,729
  • 22
  • 80
  • 110
143

I would recommend using Apache Commons Collections:

https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/CollectionUtils.html#isEmpty-java.util.Collection-

which implements it quite ok and well documented:

/**
 * Null-safe check if the specified collection is empty.
 * <p>
 * Null returns true.
 *
 * @param coll  the collection to check, may be null
 * @return true if empty or null
 * @since Commons Collections 3.2
 */
public static boolean isEmpty(Collection coll) {
    return (coll == null || coll.isEmpty());
}
noraj
  • 3,964
  • 1
  • 30
  • 38
cschaefer
  • 1,654
  • 2
  • 12
  • 10
  • 2
    Apache Utills are absolutely great! Recently I discovered SpringUtils.join - very useful using on collections. Sorry for a little offtop :) – Marcin Erbel Apr 10 '14 at 12:30
33

No, java.util.List.isEmpty() doesn't check if a list is null.

If you are using the Spring framework you can use the CollectionUtils class to check if a list is empty or not. It also takes care of the null references. Following is the code snippet from Spring framework's CollectionUtils class.

public static boolean isEmpty(Collection<?> collection) {
    return (collection == null || collection.isEmpty());
}

Even if you are not using Spring, you can go on and tweak this code to add in your AppUtil class.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78
21

This will throw a NullPointerException - as will any attempt to invoke an instance method on a null reference - but in cases like this you should make an explicit check against null:

if ((test != null) && !test.isEmpty())

This is much better, and clearer, than propagating an Exception.

pb2q
  • 58,613
  • 19
  • 146
  • 147
11

Invoking any method on any null reference will always result in an exception. Test if the object is null first:

List<Object> test = null;
if (test != null && !test.isEmpty()) {
    // ...
}

Alternatively, write a method to encapsulate this logic:

public static <T> boolean IsNullOrEmpty(Collection<T> list) {
    return list == null || list.isEmpty();
}

Then you can do:

List<Object> test = null;
if (!IsNullOrEmpty(test)) {
    // ...
}
cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • *"Does java.util.List.isEmpty() check if the list itself is null?"* seems pretty clear to me -- he is asking about the nullity of the list, not its contents. – cdhowie Jul 16 '12 at 20:37
  • Yeah, he totally confused me with such a strange question. I mean, the other way would also be dumb, because the check is for `if(!empty) then iterate`… But I deleted my stupid comment, before I saw your answer. Maybe he comes from PHP where we have `!empty($foo)` as somewhat an alias for `isset($foo) && $foo != ""`. – aufziehvogel Jul 16 '12 at 20:39
7

In addition to Lion's answer, I can say that you better use if(CollectionUtils.isNotEmpty(test)){...}.

This also checks for null, so a manual check is not needed.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
lxknvlk
  • 2,744
  • 1
  • 27
  • 32
4

Yes, it will throw an Exception. Maybe you are used to PHP code, where empty($element) does also check for isset($element). In Java this is not the case.

You can memorize that easily, because the method is directly called on the list (the method belongs to the list). So if there is no list, then there is no method. And Java will complain that there is no list to call this method on.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
aufziehvogel
  • 7,167
  • 5
  • 34
  • 56
2

You can use your own isEmpty (for multiple collection) method too. Add this to your Util class.

public static boolean isEmpty(Collection... collections) {
    for (Collection collection : collections) {
        if (null == collection || collection.isEmpty())
            return true;
    }
    return false;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Arif Acar
  • 1,461
  • 2
  • 19
  • 33
  • 3
    Maybe you ought to rename it to `areEmpty()`? I find such methods/functions harder to use because they let some stuff slip through. Also, if the first `Collection` is null or empty and the rest are neither, you'd get an unexpected behavior. – TheRealChx101 Sep 08 '18 at 22:56
  • What is the "Util class"? An existing class? Meant as a common noun? Something else? – Peter Mortensen Feb 16 '22 at 17:18
  • `containsEmpty` would be the more appropriate name – cellepo Apr 22 '22 at 23:43