一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Java Collections.EMPTY_LIST与Collections.emptyList()区别代码示例

时间:2021-11-16 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下Java 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.
     *
     * 

This example illustrates the type-safe way to obtain an empty list: *

     *     List s = Collections.emptyList();
     * 
* Implementation note: 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.) * * @see #EMPTY_LIST * @since 1.5 */ @SuppressWarnings("unchecked") public static final List emptyList() { return (List) EMPTY_LIST; }

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

以下是控制台信息

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

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

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

protected Map optionalStrParams = Collections.emptyMap();

如此修改:

protected Map optionalStrParams = new HashMap();

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

EmptyMap的背景

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

热门栏目