这是按标题、位置排序然后使用比较器排序的正确方法吗?
考虑一下这个类。
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);
}
}
如果我想按标题、位置然后顺序排序,compareTo 方法是否正确?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,您正在以错误的顺序进行比较。重新排列比较顺序将使其起作用:
No, you're making comparisons in an incorrect order. Rearranging comparisons order would make it work:
不,试试这个代码
已更新
No,Try this code
Updated
这实际上与@org.life.java的答案相同。不过,你可能会发现这个更可口。
This is actually the same as @org.life.java's answer. You might find this one more palatable, though.