List.of()或Collections.emptyList() [英] List.of() or 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屋!