使用isEmpty()方法可判断Java集合是否为空,适用于List、Set等Collection接口及Map类型,需注意null与空集合区别,避免NullPointerException。

在Java中判断集合是否为空,关键在于使用集合提供的 isEmpty() 方法。这个方法适用于所有实现 Collection 接口的集合类型,比如 List、Set、Queue 等,也包括 Map(虽然Map不是Collection,但它也有 isEmpty() 方法)。
isEmpty() 方法返回一个布尔值:
示例代码:
List<String> list = new ArrayList<>();
if (list.isEmpty()) {
System.out.println("集合为空");
} else {
System.out.println("集合不为空");
}
集合变量本身可能是 null,这和“空集合”是两个概念:
立即学习“Java免费学习笔记(深入)”;
list == null:表示引用未指向任何对象list.isEmpty():表示对象存在但没有元素如果对一个 null 集合调用 isEmpty(),会抛出 NullPointerException。因此,在判断前最好先检查是否为 null:
if (list == null || list.isEmpty()) {
System.out.println("集合为 null 或为空");
}
为了安全起见,可以封装或直接使用如下模式:
public static <T> boolean isNullOrEmpty(Collection<T> collection) {
return collection == null || collection.isEmpty();
}
这样可以在一行中安全判断集合是否为 null 或空。
基本上就这些。使用 isEmpty() 是标准做法,比判断 size() == 0 更清晰且语义更准确。同时记得处理 null 情况,避免运行时异常。
以上就是如何在Java中判断集合是否为空的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号