使用Collections.emptyList()和emptyMap()可避免null,提升代码健壮性与性能。它们返回全局唯一的不可变空集合实例,防止NPE,减少内存开销,适用于API返回值、字段默认值等无需修改的场景。

在Java开发中,
Collections.emptyList()
Collections.emptyMap()
NullPointerException
Collections.emptyList()
Collections.emptyMap()
java.util.Collections
UnsupportedOperationException
这其实是个老生常谈的话题了,但每次提到,我总觉得还是很有必要强调一下:避免
null
NullPointerException
null
想象一下,你有一个服务方法,它负责查询用户列表。如果查询结果为空,你是返回
null
立即学习“Java免费学习笔记(深入)”;
如果返回
null
List<User> users = userService.findUsersByCriteria(criteria);
if (users != null) { // 每次调用后都得加这个判断
for (User user : users) {
// ... 处理用户 ...
}
}这种代码,到处都是
if (xxx != null)
而如果返回
Collections.emptyList()
List<User> users = userService.findUsersByCriteria(criteria); // 即使没有用户,也总是一个非null的列表
for (User user : users) { // 可以直接迭代,无需担心NPE
// ... 处理用户 ...
}是不是清爽很多?调用者不需要关心底层有没有数据,只要它拿到的是一个
List
这两个选项虽然都能得到一个空的集合,但它们的本质和用途却大相径庭,理解它们之间的差异,能帮助你做出更明智的选择。
最核心的区别在于可变性和内存效率。
new ArrayList()
new HashMap()
而
Collections.emptyList()
Collections.emptyMap()
UnsupportedOperationException
EmptyList
EmptyMap
所以,如果你需要一个可以随时填充数据的集合,即使它开始是空的,也应该使用
new ArrayList()
new HashMap()
Collections.emptyList()
Collections.emptyMap()
在我日常的开发工作中,我发现有几个场景是
Collections.emptyList()
Collections.emptyMap()
API 方法的返回值: 这是最常见的场景。当你的业务逻辑在某些条件下没有数据可返回时,比如一个查询方法没有找到匹配项,或者一个聚合操作结果为空,返回一个空集合而非
null
public List<Order> getRecentOrders(String userId) {
// 假设这里是数据库查询逻辑
List<Order> orders = databaseService.findOrdersByUserId(userId);
if (orders.isEmpty()) {
return Collections.emptyList(); // 明确表示没有订单,而不是null
}
return orders;
}类的字段默认值: 有时候一个类的某个列表或映射字段,在对象刚创建时可能没有数据,但你又不想把它初始化为
null
Collections.emptyList()
Collections.emptyMap()
public class Product {
private String name;
private List<String> tags = Collections.emptyList(); // 默认一个空标签列表,避免NPE
public Product(String name) {
this.name = name;
}
// 如果需要添加标签,通常会创建一个新的可变列表
public void addTag(String tag) {
if (this.tags == Collections.emptyList()) { // 如果是默认的空列表
this.tags = new ArrayList<>(); // 第一次添加时才实例化可变列表
}
((ArrayList<String>) this.tags).add(tag);
}
public List<String> getTags() {
return tags;
}
}请注意,这里
addTag
tags
Collections.emptyList()
ArrayList
作为 Stream API 的初始值或聚合结果: 在使用Java Stream API进行数据处理时,如果某个
collect
Collections.emptyList()
List<String> validNames = names.stream()
.filter(name -> name != null && !name.trim().isEmpty())
.collect(Collectors.toList()); // collect默认不会返回null
// 但如果你的自定义收集器或者其他逻辑可能导致空,可以考虑
// return validNames.isEmpty() ? Collections.emptyList() : validNames;当然,
Collectors.toList()
ArrayList
Optional
在某些条件逻辑分支中: 当程序根据特定条件,需要返回一个明确的“无数据”状态时,它们同样适用。
总而言之,只要你希望表达一个集合是空的,并且它在后续的生命周期中不应该被修改,那么
Collections.emptyList()
Collections.emptyMap()
null
new ArrayList()
以上就是Java中Collections.emptyList和Collections.emptyMap使用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号