Effective Java(第二版)第43条-返回零长度的数据或者集合,而不是NULL

1. Motivation:

今天做syn order的时候,碰到一个错误,查了半天,发现是因为在判断一个ArrayList是否为空时忘了首先判断该对象是否为空,大致的错误场景如下代码所示:

public static void main(String[] args) {
   List<String>_elements = getAllElemnts();
   if(_elements.isEmpty()) {
     System.out.println("I am OK!");
   }
}

public List<String> getAllElements() {
  return null;
}

不注意的话,经常会犯这种小错误,为了避免出现这种错误,Effective Java里面的第43条提供了一条妙方。

2.返回零长度的数组或是集合,而不是null
Effective Java第43条讲到,为了避免1中错误, 应尽量避免返回null,而是用零长度数组或是集合代替。
废话不多说,直接上代码:

public static void main(String[] args) {
   List<String>_elements = getAllElemnts();
   if(_elements.isEmpty()) {
     System.out.println("I am OK!");
   }
}

public List<String> getAllElements() {
  return Collections.emptyList();
}

当返回值为数组时,应返回零长度数组,代码为:

public static void main(String[] args) {
   List<String>_elements = getAllElemnts();
   if(_elements.isEmpty()) {
     System.out.println("I am OK!");
   }
}
public List<String> getAllElements() {
  return new String[0];
}

当然,此时,每次都要初始化一个零长度的数组,为避免这种资源的浪费,可以再类中定义一个静态变量即为:

public static void main(String[] args) {
   String[]_elements = getAllElemnts();
   if(_elements.isEmpty()) {
     System.out.println("I am OK!");
   }
}

public String[] getAllElements() {
  return EMPTY_STR;
}

private static final String[] EMPTY_STR = new String[0];

3. 返回空map及set

在项目中,大多使用Collection,如Set, Map等,上文中讲到了当返回值为空List是返回Collections.emptyList(),同样的,Collections库里也有emptyMap(), emptySet(),

即为:

public static void main(String[] args) {
   Map<String>_elements = getAllElemnts();
   if(_elements.isEmpty()) {
     System.out.println("I am OK!");
   }
}

public Map<String> getAllElements() {
  return Collections.emptyMap();
}

public static void main(String[] args) {
   Set<String>_elements = getAllElemnts();
   if(_elements.isEmpty()) {
     System.out.println("I am OK!");
   }
}

public List<String> getAllElements() {
  return Collections.emptySet();
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值