问题
Consider this class.
public class DynamicField implements Comparable<DynamicField> {
String title;
int position;
int order;
@Override
public int compareTo(DynamicField o) {
if(position < o.position)
return -1;
if(position > o.position)
return 1;
if(order < o.order)
return -1;
if(order > o.order)
return 1;
return title.compareTo(o.title);
}
}
Is the compareTo method correct if I want to sort by title, position and then order?
回答1:
No, you're making comparisons in an incorrect order. Rearranging comparisons order would make it work:
@Override
public int compareTo(DynamicField o) {
int c = title.compareTo(o.title);
if (c != 0)
return c;
if(position < o.position)
return -1;
if(position > o.position)
return 1;
if(order < o.order)
return -1;
if(order > o.order)
return 1;
return 0;
}
回答2:
No,Try this code Updated
public class DynamicField implements Comparable<DynamicField> {
String title;
int position;
int order;
@Override
public int compareTo(DynamicField o) {
int result = title.compareTo(o.title);
if(result != 0) {}
else if(position != o.position)
result = position-o.position;
else if(order != o.order)
result = order- o.order;
return result;
}
}
回答3:
This is actually the same as @org.life.java's answer. You might find this one more palatable, though.
@Override
public int compareTo() {
int result = title.compareTo(o.title);
if (result == 0)
result = position - o.position;
if (result == 0)
result = order - o.order;
return result;
}
来源:https://stackoverflow.com/questions/3823608/is-this-a-correct-way-of-sorting-by-title-position-and-then-order-by-using-a-co