平常看项目源代码,我们可以发现,很多集合都有如下类似的写法
List<String> mList = Collections.EMPTY_LIST;
Set<String> mSet = Collections.EMPTY_SET;
Map<String> mMap = Collections.EMPTY_MAP;
关于这个引用 Effective Java 一书中有明确的提到,如下:
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 Effective Java,Item #15 “Minimize Mutability”.
From Collections-emptySet-Collections-emptyList-Collections-emptyMap
Its a type of programming idiom. This is for people that do not want null variables. So before the set get initialized, they can use the empty set.
**Note:**Below clode is just example(change it according to your use case)
private Set myset = Collections.emptySet();
void putData() {
mySet.add("test")
}
void initSet() {
myset = new HashSet();
}
void initSet2() {
myset = new HashSet<String>();
}
void initSet3() {
myset = new HashSet<Integer>();
}
void deleteSet() {
myset = Collections.emptySet();
}
These methods offer o 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.
以上内容摘录自 Effective Java 第43条
Collections.emptyList(),Collections.emptySet(),Collections.emptyMap(),返回的是一个空数组或者一个空集合而不是空对象,同时这三个方法声明的集合符合了Effective Java 15条 减少不可变,代码快的initSet(),initSet2(),initSet3(),就证明了可以在使用的时候动态定义自己集合或者数组所要存放的数据类型.同时代码快的mySet变量的声明保证了不为空,并引用已经存在的空的数组或者集合且不可变的对象,这个也可以防止代码中set集合没有初始化为空的可能。对于以上数组或者集合的声明方法,effective java中是这么说的这种影响通常是很小的,但它的偶尔(以及,很少)重要。