我实现compareTo()方法为一个简单的类,这样(以便能够使用Collections.sort()和其他好处提供的Java平台):
public class Metadata implements Comparable {
private String name;
private String value;
// Imagine basic constructor and accessors here
// Irrelevant parts omitted
}
我希望这些对象的自然排序是:1)按名称排序,2)如果名称相同,按值排序;两个比较应该不区分大小写。对于这两个字段,null值是完全可以接受的,因此compareTo在这些情况下不能中断。
想到的解决方案是沿着以下线(我在这里使用“保护子句”,而其他人可能更喜欢一个单一的返回点,但这是在点):
// primarily by name, secondarily by value; null-safe; case-insensitive
public int compareTo(Metadata other) {
if (this.name == null && other.name != null){
return -1;
}
else if (this.name != null && other.name == null){
return 1;
}
else if (this.name != null && other.name != null) {
int result = this.name.compareToIgnoreCase(other.name);
if (result != 0){
return result;
}
}
if (this.value == null) {
return other.value == null ? 0 : -1;
}
if (other.value == null){
return 1;
}
return this.value.compareToIgnoreCase(other.value);
}
这做的工作,但我不是完全满意这个代码。诚然,它不是很复杂,但是相当冗长和乏味。
问题是,你将如何使这更少冗长(同时保留功能)?如果他们帮助,请随意参考Java标准库或Apache Commons。将这个(一点)更简单的唯一选项是实现我自己的“NullSafeStringComparator”,并应用它来比较这两个字段?
编辑1-3:Eddie的权利;固定“两个名称都为null”上面的情况