在 Java 中检查集合是否为空:哪个是最好的方法? [英] Checking if a collection is empty in Java: which is the best method?

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

问题描述

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

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.

谁能解释一下?

推荐答案

你应该绝对使用 isEmpty().计算任意列表的 size() 可能很昂贵.当然,即使验证它是否有任何元素可能很昂贵,但是对于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缓存).然后 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 中检查集合是否为空:哪个是最好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆