Comparable
合同规定e.compareTo(null)
必须扔NullPointerException
.
From the API http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html:
注意null
不是任何类的实例,并且e.compareTo(null)
应该抛出一个NullPointerException
虽然e.equals(null)
回报false
.
另一方面,Comparator API http://java.sun.com/javase/6/docs/api/java/util/Comparator.html没有提到比较时需要发生什么null
。考虑以下通用方法的尝试,该方法采用Comparable
,并返回一个Comparator
因为它把null
作为最小元素。
static <T extends Comparable<? super T>> Comparator<T> nullComparableComparator() {
return new Comparator<T>() {
@Override public int compare(T el1, T el2) {
return
el1 == null ? -1 :
el2 == null ? +1 :
el1.compareTo(el2);
}
};
}
这使我们能够执行以下操作:
List<Integer> numbers = new ArrayList<Integer>(
Arrays.asList(3, 2, 1, null, null, 0)
);
Comparator<Integer> numbersComp = nullComparableComparator();
Collections.sort(numbers, numbersComp);
System.out.println(numbers);
// "[null, null, 0, 1, 2, 3]"
List<String> names = new ArrayList<String>(
Arrays.asList("Bob", null, "Alice", "Carol")
);
Comparator<String> namesComp = nullComparableComparator();
Collections.sort(names, namesComp);
System.out.println(names);
// "[null, Alice, Bob, Carol]"
所以问题是:
- 这是可接受的使用吗
Comparator
,或者是否违反了有关比较的不成文规则null
和投掷NullPointerException
?
- 甚至必须对一个问题进行排序是个好主意吗?
List
含有null
元素,或者这是设计错误的明确标志?