Checking if a collection is empty in Java: which is the best method?

后端 未结 11 1550
醉话见心
醉话见心 2020-12-01 01:27

I have two ways of checking if a List is empty or not

if (CollectionUtils.isNotEmpty(listName)) 

and

if (listName != null          


        
相关标签:
11条回答
  • 2020-12-01 01:45

    I would use the first one. It is clear to see right away what it does. I dont think the null check is necessary here.

    0 讨论(0)
  • 2020-12-01 01:52

    You should absolutely use isEmpty(). Computing the size() of an arbitrary list could be expensive. Even validating whether it has any elements can be expensive, of course, but there's no optimization for size() which can't also make isEmpty() faster, whereas the reverse is not the case.

    For example, suppose you had a linked list structure which didn't cache the size (whereas LinkedList<E> does). Then size() would become an O(N) operation, whereas isEmpty() would still be O(1).

    Additionally of course, using isEmpty() states what you're actually interested in more clearly.

    0 讨论(0)
  • 2020-12-01 01:52
    isEmpty()
    
          Returns true if this list contains no elements.
    

    http://docs.oracle.com/javase/1.4.2/docs/api/java/util/List.html

    0 讨论(0)
  • 2020-12-01 01:56

    Apache Commons' CollectionUtils.isNotEmpty(Collection) is a NULL-SAFE check

    Returns TRUE is the Collection/List is not-empty and not-null Returns FALSE if the Collection is Null

    Example:

    List<String> properties = new ArrayList();
    ...
    if (CollectionUtils.isNotEmpty(properties)) {
      // process the list
    } else {
     // list is null or empty
    }
    

    Refer: https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/CollectionUtils.html#isNotEmpty(java.util.Collection)

    0 讨论(0)
  • 2020-12-01 01:58

    If you have the Apache common utilities in your project rather use the first one. Because its shorter and does exactly the same as the latter one. There won't be any difference between both methods but how it looks inside the source code.

    Also a empty check using

    listName.size() != 0
    

    Is discouraged because all collection implementations have the

    listName.isEmpty()
    

    function that does exactly the same.

    So all in all, if you have the Apache common utils in your classpath anyway, use

    if (CollectionUtils.isNotEmpty(listName)) 
    

    in any other case use

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

    You will not notice any performance difference. Both lines do exactly the same.

    0 讨论(0)
提交回复
热议问题