I have an array of a custom type that I want to sort by one of its String attributes. For some reason, the following code is producing wrong results. Could you point out where I might have made a mistake?
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;
}
}
One problem to start with – your comparator is inconsistent if you give it two patients with null names, or two null patient references. In particular:
The signs of
xandyought to be different – but they’ll both be -1.After that, it depends on how you want to compare the names. I would usually use
if you want to sort in ascending order. Note that to sort in descending order you shouldn’t just return
-p1_LN.compareTo(p2_LN), as if the comparison returns the Integer.MIN_VALUE, the negation won’t work. Instead you’d want to returnp2_LN.compareTo(p1_LN);.Note that if you’re using this scheme, you don’t need to call
p1_LN.equals(p2_LN)either – that will be handled by thecompareTocall.