I have two ways of checking if a List is empty or not
if (CollectionUtils.isNotEmpty(listName))
and
if (listName != null && listName.size() != 0)
My arch tells me that the former is better than latter. But I think the latter is better.
Can anyone please clarify it?
You should absolutely use
isEmpty(). Computing thesize()of an arbitrary list could be expensive. Even validating whether it has any elements can be expensive, of course, but there’s no optimization forsize()which can’t also makeisEmpty()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). Thensize()would become an O(N) operation, whereasisEmpty()would still beO(1).Additionally of course, using
isEmpty()states what you’re actually interested in more clearly.