我有一个自定义类型的数组,我想通过它的一个String属性进行排序。出于某种原因,下面的代码产生错误的结果。你能指出我可能犯了什么错误吗?通过字符串属性对自定义类型数组排序?
class PatientLNComparator implements Comparator<Patient>{
@Override
public int compare(Patient p1, Patient p2) {
String p1_LN = (p1 == null) ? null : p1.last_name;
String p2_LN = (p2 == null) ? null : p2.last_name;
if(p2_LN == null)
return -1;
else if(p1_LN == null)
return +1;
else if(p1_LN.equals(p2_LN))
return 0;
else if(p1_LN.compareTo(p2_LN) > 0)
return -1;
else
return +1;
}
}
你能给出一个错误结果的例子吗?初步看来我认为你在compareTo行中翻转了标志 – 2011-02-03 00:11:21
由于所有的空检查都是先完成的,你可以删除`p2_LN`和`p1_LN`。 – Brian 2011-02-03 19:11:25