Collections.emptyList()vs. new instance [英] Collections.emptyList() vs. new instance

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

问题描述

实际上,最好是返回一个空列表,例如 this

  return Collections.emptyList 

或像

  new ArrayList< Foo>(); 

还是这完全取决于你要对返回的列表做什么?

解决方案

主要区别是 Collections.emptyList() 返回列表中,即不能添加元素的列表。



在您 列表,因此不会是一个选项。



我会说,返回一个不可变的列表是完全正确的(甚至首选的方式)只要合同

此外, emptyList()

$ c> 可能不会创建新对象


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


emptyList 如下所示:

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

所以如果你的方法(返回一个空列表)这种方法甚至可以给你稍微更好的性能的CPU和内存聪明。


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

return Collections.emptyList();

Or like this:

return new ArrayList<Foo>();

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

解决方案

The main difference is that Collections.emptyList() returns an immutable list, i.e., a list to which you cannot add elements.

In the rare cases in which you do want to modify the returned list, this would thus not be an option.

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.


In addition, emptyList() might not create a new object with each call.

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

The implementation of emptyList looks as follows:

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

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()vs. new instance的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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