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

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

    if (CollectionUtils.isNotEmpty(listName))

    Is the same as:

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

    In first approach listName can be null and null pointer exception will not be thrown. In second approach you have to check for null manually. First approach is better because it requires less work from you. Using .size() != 0 is something unnecessary at all, also i learned that it is slower than using .isEmpty()

提交回复
热议问题