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

问题描述

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

  return Collections.emptyList 

或像:

  new ArrayList< Foo>(); 

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

解决方案

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



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



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

此外, emptyList()

$ c>

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.

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

09-12 01:40