List.of()或Collections.emptyList() [英] List.of() or Collections.emptyList()

查看:153
本文介绍了List.of()或Collections.emptyList()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为 List.of(...)或Collections.unmodifiableList()的特殊情况, - 指向不可变列表的首选Java 9方式是什么?

As an special case of List.of(...) or Collections.unmodifiableList() - what is the preferred Java 9 way of pointing to an empty and immutable list?

继续撰写

Collections.emptyList();

或切换到

List.of();


推荐答案

Collections.emptyList 不需要为每个调用创建一个新对象;通常,在OpenJDK 中,只返回单例 EMPTY_LIST 对象。此外,更清楚的是,您打算意指一个空列表,而不是忘记填写一个占位符。

Collections.emptyList() does not need to create a new object for each call; it's typical, as in OpenJDK, to just return the singleton EMPTY_LIST object. Additionally, it's clearer that you intend to mean an empty list rather than having forgotten to fill in a placeholder.

使用 emptyList();它更快,更易读。

Use emptyList(); it's both faster and more readable.

这篇关于List.of()或Collections.emptyList()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆