在哪些情况下我可以使用Collections.emptyMap()
?文件上说,如果我想让我的Collection 保持不变,我可以使用这种方法.
Why would I want an immutable empty collection? What is the point?个
在哪些情况下我可以使用Collections.emptyMap()
?文件上说,如果我想让我的Collection 保持不变,我可以使用这种方法.
Why would I want an immutable empty collection? What is the point?个
从Effective Java、Item #43到"Return empty arrays or collections, not null"
演示了返回一个空集合,甚至可能演示了在Collections类上使用这些emptyList()
、emptySet()
和emptyMap()
方法来获得一个空集合,该集合还具有不可变的额外好处.从Item #15到"Minimize Mutability"
.
从Collections-emptySet-Collections-emptyList-Collections
这是一种编程习惯.这是为那些不想要空变量的人准备的.所以在初始化集合之前,他们可以使用空集合.
下面的Note:个代码只是一个示例(根据您的用例进行更改):
private Set myset = Collections.emptySet();
void initSet() {
myset = new HashSet();
}
void deleteSet() {
myset = Collections.emptySet();
}
这些方法有两个优点:
它们更简洁,因为您不需要显式地键入集合的泛型类型——它通常只是从方法调用的上下文推断出来的.
它们效率更高,因为它们不需要创建新对象;它们只是重复使用现有的空且不可变的对象.这种影响通常很小,但偶尔(嗯,很少)很重要.