Java中Collections.EMPTY_LIST与Collections.emptyList()的区别有哪些

发布时间:2021-11-16 17:20:42 作者:小新
来源:亿速云 阅读:176

这篇文章将为大家详细讲解有关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()引起的一个奇怪的问题

以下是控制台信息

Java中Collections.EMPTY_LIST与Collections.emptyList()的区别有哪些

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

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

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

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

如此修改:

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

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

关于“Java中Collections.EMPTY_LIST与Collections.emptyList()的区别有哪些”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

推荐阅读:
  1. Trufun UML工具代码生成功能视频演示
  2. JAVA中枚举的特性有哪些

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:Go语言中net包RPC远程调用方式有哪些

下一篇:优化iOS程序性能的二十五个方法分别是哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》