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

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

提交回复
热议问题