Java Collections.EMPTY_LIST与Collections.emptyList()的区别

 更新时间:2021年11月16日 15:31:44   作者:范亚明  
这篇文章主要介绍了Java Collections.EMPTY_LIST与Collections.emptyList()的区别,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

Collections.EMPTY_LIST与Collections.emptyList()的区别

Collections.EMPTY_LIST返回的是一个空的List。为什么需要空的List呢?有时候我们在函数中需要返回一个List,但是这个List是空的,如果我们直接返回null的话,调用者还需要进行null的判断,所以一般建议返回一个空的List。

Collections.EMPTY_LIST返回的这个空的List是不能进行添加元素这类操作的。这时候你有可能会说,我直接返回一个new ArrayList()呗,但是new ArrayList()在初始化时会占用一定的资源,所以在这种场景下,还是建议返回Collections.EMPTY_LIST。

Collections. emptyList()返回的也是一个空的List,它与Collections.EMPTY_LIST的唯一区别是,Collections. emptyList()支持泛型,所以在需要泛型的时候,可以使用Collections. emptyList()。

Collections.EMPTY_MAP和Collections.EMPTY_SET同理。

Collections.EMPTY_LIST的实现代码

    /**
     * The empty list (immutable).  This list is serializable.
     *
     * @see #emptyList()
     */
    @SuppressWarnings("unchecked")
    public static final List EMPTY_LIST = new EmptyList<>();

Collections. 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<String> 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
     */
    @SuppressWarnings("unchecked")
    public static final <T> List<T> emptyList() {
        return (List<T>) EMPTY_LIST;
}

使用Collections.emptyMap()引起的一个奇怪的问题

以下是控制台信息

第二行是很不起眼的一条异常信息,不知为何没有把整个错误堆栈输出。

一开始没有注意到这条异常信息,于是设断点,调试,结果每次执行几句就莫名其妙地转入ThreadPoolExecutor中执行。

最后注意到上面的异常信息后,发现对一个类型为Map的成员变量初始化有问题:

protected Map<String, String> optionalStrParams = Collections.emptyMap();

如此修改:

protected Map<String, String> optionalStrParams = new HashMap<String, String>();

我的本意是初始化为一个空的Map,EmptyMap在此场景下不合适。

EmptyMap的背景

在某些情况下,我们经常需要发挥一个空的集合对象,比如说在数据查询时,并不需要发挥一个NULL或是异常,那么就可以返回一个空的集合对象。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

最新评论