Collections.emptyMap()vs new HashMap() [英] Collections.emptyMap() vs new HashMap()
问题描述
在某些情况下,我可以使用 Collections.emptyMap()
?文档说我可以使用这种方法,如果我想我的集合是不可变的。
为什么我想要一个不可变的空集合? ,项目# 43 - 返回空数组或集合,非空
演示返回一个空集合,甚至可以演示使用这些 emptyList /Class.class方法的$ / code>,
,emptySet()
和集合还具有不可变的附加好处。 Item#15
最小化可变性
。
http://www.coderanch.com/t/536728/java/java/Collections-emptySet-Collections-emptyList-Collections\">Collections-emptySet-Collections-emptyList-Collections
它是一种编程习语。这是为不需要空变量的人。所以在set被初始化之前,他们可以使用空集。
注意:下面的代码只是一个示例(根据用例更改) p>
private Set myset = Collections.emptySet();
void initSet(){
myset = new HashSet();
}
void deleteSet(){
myset = Collections.emptySet();
}
这些方法有几个优点:
-
它们更简洁,因为您不需要显式地输出集合的通用类型 - 它通常只是从方法调用的上下文。
-
它们更有效率,因为他们不打扰创建新对象;他们只是重用一个现有的空和不可变的对象。
这个效果通常很小,但偶尔
What are some of the situations where I can use Collections.emptyMap()
? The Documentation says I can use this method if I want my collection to be immutable.
Why would I want an immutable empty collection? What is the point?
From Effective Java, Item #43 - "Return empty arrays or collections, not null"
demonstrates returning an empty collection and perhaps even demonstrates using these emptyList()
, emptySet()
, and emptyMap()
methods on the Collections class to get an empty collection that also has the additional benefit of being immutable. From Item #15 "Minimize Mutability"
.
From Collections-emptySet-Collections-emptyList-Collections
Its a type of programming idiom. This is for people that do not want null variables. So before the set gets initialized, they can use the empty set.
Note: Below code is just an example (change it according to your use case):
private Set myset = Collections.emptySet();
void initSet() {
myset = new HashSet();
}
void deleteSet() {
myset = Collections.emptySet();
}
These methods offer a couple of advantages:
They're more concise because you don't need to explicitly type out the generic type of the collection - it's generally just inferred from the context of the method call.
They're more efficient because they don't bother creating new objects; they just re-use an existing empty and immutable object. This effect is generally very minor, but it's occasionally (well, rarely) important.
这篇关于Collections.emptyMap()vs new HashMap()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!