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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

范亚明   2021-11-16 我要评论
想了解Java Collections.EMPTY_LIST与Collections.emptyList()的区别的相关内容吗,范亚明在本文为您仔细讲解Collections.EMPTY_LIST与Collections.emptyList()区别的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java,Collections.EMPTY_LIST,Java,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或是异常,那么就可以返回一个空的集合对象。

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们