为什么有人会在 Java 中使用 Collections.emptyList?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12597277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:29:48  来源:igfitidea点击:

Why would someone use Collections.emptyList in java?

javalistcollections

提问by Hossein

Possible Duplicate:
Collections.emptyList() vs. new instance

可能的重复:
Collections.emptyList() 与新实例

I was trying to understand the difference between create a new instance of a list using:

我试图了解使用以下方法创建列表的新实例之间的区别:

new ArrayList<X>

and

Collections.emptyList();

As I understood, the later returns an immutable list. That means that it is not possible to add,delete, or modify it. I want to know why one would create and immutable emptyList ? what is the use? thanks

据我了解,后者返回一个不可变的列表。这意味着无法添加、删除或修改它。我想知道为什么要创建不可变的 emptyList ?有什么用?谢谢

回答by Thilo

Being immutable allows for reusable instances.

不可变允许可重用​​的实例。

Collections.emptyList will always return the exact same singleton instance.

Collections.emptyList 将始终返回完全相同的单例实例。

This is very efficient.

这是非常有效的。

In addition to that, immutable data can be safely shared between threads, and is guaranteed to avoid weird side-effects due to coding errors. For that reason it makes defensive copies unnecessary, too.

除此之外,不可变数据可以安全地在线程之间共享,并保证避免由于编码错误引起的奇怪的副作用。出于这个原因,它也使得防御性副本变得不必要。

回答by Peter Lawrey

Say you have to return a collection and you don't want to creating a couple of objects each time.

假设您必须返回一个集合并且您不想每次都创建几个对象。

interface Configurable {
    List<String> getConfigurationList();
}

// class which doesn't have any configuration
class SimpleConfigurable implements Configurable {
    public List<String> getConfigurationList() { return Collections.emptyList(); }
}

Returning an empty collection is often preferable to returning null

返回空集合通常比返回更可取 null

回答by Sébastien Le Callonnec

I often use empty lists as Null objects: this avoid having to check for null.

我经常使用空列表作为Null 对象:这样可以避免检查null.

回答by Matti Lyra

I've used Collections.emptyListfor methods that return a list but that are called with arguments that don't make sense.

我已经用于Collections.emptyList返回列表但使用没有意义的参数调用的方法。

For instance a stream processing application where you want to access different parts of the stream, perhaps based on dates. You query for a time span of items from the stream but if there are no items in that time span you would return an empty list. Throwing an exception wouldn't make any sense since the isn't anything wrong with the query. Returning nullalso doesn't make much sense because then all the calling code needs to check for null.

例如,您希望访问流的不同部分(可能基于日期)的流处理应用程序。您从流中查询项目的时间跨度,但如果该时间跨度内没有项目,您将返回一个空列表。抛出异常没有任何意义,因为查询没有任何问题。返回null也没有多大意义,因为所有调用代码都需要检查null.

Returning an immutable empty list allows the calling code the handle the return value nicely, you don't need to worry about threading issues since an immutable list is inherently thread safe.

返回一个不可变的空列表允许调用代码很好地处理返回值,您无需担心线程问题,因为不可变列表本质上是线程安全的。

回答by Arnab Biswas

To avoid Unwanted NullPointerException.

避免不需要的 NullPointerException。

In your code, you may return a normal "empty" ArrayList instead of returning null. But, in that way, you will keep creating NEW objects (with default capacity of 10) on each execution which is not a memory efficient approach. Instead of that if you return emptyList, the same instance will be returned on every invocation. This way it saves you from unwanted NullPointerException in a more efficient way. Here is the snip from the Javadoc for emptyList:

在您的代码中,您可能会返回一个普通的“空”ArrayList 而不是返回 null。但是,通过这种方式,您将在每次执行时不断创建新对象(默认容量为 10),这不是一种内存高效的方法。如果您返回emptyList,则相反,每次调用都会返回相同的实例。这样,它以更有效的方式将您从不需要的 NullPointerException 中拯救出来。这是来自 Javadoc 的 emptyList 片段:

/**
 * Returns the empty list (immutable).  This list is serializable.
 *
 * <p>This example illustrates the type-safe way to obtain an empty list:
 * <pre>
 *     List&lt;String&gt; s = Collections.emptyList();
 * </pre>
 * Implementation note:  Implementations of this method need not
 * create a separate <tt>List</tt> 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.)
 *
 * @see #EMPTY_LIST
 * @since 1.5
 */