我们经常可以看到这样的代码:
private final List<Cheese> cheesesInStock = ...;
/**
* @return an array containing all of the cheeses in the shop,
* or null if no cheese are available for purchase.
*/
public Cheese[] getCheeses(){
if(cheesesInStock.size() == 0)
return null;
...
}
那么客户端要额外处理:
Cheese[] cheeses = shop.getCheeses();
if(chesses != null && Arrays.asList(cheeses).contains(Chees.STILTON))
System.out.println("Joll good, just the thing.");
而如果是这样,该多好
if(Arrays.asList(cheeses).contains(Chees.STILTON))
System.out.println("Joll good, just the thing.");
所以说返回null的话,每次都要进行这种类型判断,否则很容易出现空指针异常的现象,而且也很容易忘记判断,所以要避免返回null结果。
常用做法:返回类型是数组或者集合时,避免返回null
1.数组做法:
因为零长度的数组是不可变的,所以它可以作为一个共享的对象。
private final Girl[] NO_GIRL = new Girl[0];
public Girl[] getGirl() {
return NO_GIRL;
}
2.集合做法:
集合值的方法也可以做成在每当需要返回同一个不可变的空集合。Collections.emptySet、emptyList和emptyMap方法提供的正是你需要的。
public List< Girl > getGirl(){
return Collections.emptyList();
}