本文介绍了检查Java中的集合是否为空:哪种方法最好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种检查List是否为空的方法

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

if (CollectionUtils.isNotEmpty(listName))

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?

推荐答案

绝对使用 isEmpty()。计算任意列表的 size()可能很昂贵。当然,即使验证它是否有 的任何元素都很昂贵,但 c> size()的优化也不能 使 isEmpty()更快,反之则不然。

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.

例如,假设你有一个链接列表结构没有缓存大小(而 LinkedList< E> )。然后 size()将成为O(N)操作,而 isEmpty()仍然是 O(1)

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).

此外,使用 isEmpty()用更清楚的方式陈述你真正感兴趣的东西。

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

这篇关于检查Java中的集合是否为空:哪种方法最好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:53