Java中数组或集合声明使用的一个小技巧

平常看项目源代码,我们可以发现,很多集合都有如下类似的写法

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中是这么说的这种影响通常是很小的,但它的偶尔(以及,很少)重要。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值