Collections.emptyList() 与新实例 [英] Collections.emptyList() vs. new instance

查看:18
本文介绍了Collections.emptyList() 与新实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在实践中,返回一个像 这个:

In practice, is it better to return an empty list like this:

return Collections.emptyList();

或者像这个:

return new ArrayList<Foo>();

或者这完全取决于您将如何处理返回的列表?

Or is this completely dependent upon what you're going to do with the returned list?

推荐答案

主要区别在于 Collections.emptyList() 返回一个 不可变 列表,即您要添加到的列表无法添加元素.(同样适用于 List.of() 在 Java 9 中引入.)

The main difference is that Collections.emptyList() returns an immutable list, i.e., a list to which you cannot add elements. (Same applies to the List.of() introduced in Java 9.)

在极少数情况下,您确实想要修改返回的列表,Collections.emptyList()List.of() 是因此不是一个好的选择.

In the rare cases where you do want to modify the returned list, Collections.emptyList() and List.of() are thus not a good choices.

我会说,只要合同(文档)没有明确规定不同,返回一个不可变列表就完全没问题(甚至是首选方式).

I'd say that returning an immutable list is perfectly fine (and even the preferred way) as long as the contract (documentation) does not explicitly state differently.

另外,emptyList() 可能不会在每次调用时创建一个新对象.

该方法的实现不需要为每次调用创建一个单独的 List 对象.使用此方法的成本可能与使用同名字段的成本相当.(与此方法不同,该字段不提供类型安全.)

Implementations of this method need not create a separate List object for each call. Using this method is likely to have comparable cost to using the like-named field. (Unlike this method, the field does not provide type safety.)

emptyList 的实现如下:

public static final <T> List<T> emptyList() {
    return (List<T>) EMPTY_LIST;
}

因此,如果您的方法(返回一个空列表)被频繁调用,这种方法甚至可以在 CPU 和内存方面为您提供稍微更好的性能.

So if your method (which returns an empty list) is called very often, this approach may even give you slightly better performance both CPU and memory wise.

这篇关于Collections.emptyList() 与新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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