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

后端 未结 11 1607
醉话见心
醉话见心 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: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.

提交回复
热议问题