
对于一个返回null 而不是零长度数组或者集合的方法,客户端几乎每次用到该方法都可能会忘记写专门处理null 返回值的代码,进而导致NPE。
有时候会有程序员认为:null 返回值比零长度数组更好,因为它避免了分配数组所需要的开销,但这种观点站不住脚。
返回空数组,可以使用集合实现类的toArray()方法,例如:ArrayList.toArray():
private final List<Cheese> cheeseList = new ArrayList<>();
private static final Cheese[] EMPTY_CHEESE_ARRAY = new Cheese[0];
public Cheese[] getCheese(){
// 返回空数组
return cheeseList.toArray(EMPTY_CHEESE_ARRAY);
}返回空集合,可以使用Collections.emptySet(),Collections.emptyMap(),Collections.emptyList():
public List<Cheese> getCheeseList() {
if (cheeseList.isEmpty()){
// 返回一个不可变的空集合:emptySet/emptyMap/emptyList,这三个
return Collections.emptyList();
} else {
return new ArrayList<Cheese>(cheeseList);
}
}简而言之,返回类型为数组或集合的方法,没理由返回null,二是返回一个零长度的数组或者集合。
Java 的返回值为null 的做法,很可能是从C 语言沿袭过来的,在C 中,数组长度是与实际的数组分开返回的,如果返回的数组长度为0,再分配一个数组就没有任何好处了。