java实现两个元素的比较
我试图这样覆盖可比较的内容:
public int compareTo(Object other) {
if(other.getlength() > this.getlength()){
return 1;
} else if (other.getlength() < this.getlength()){
return -1;
} else {
if (other.getVal() > this.getVal()){
return 1;
} else {
return -1;
}
}
}
我想要发生的事情是首先按长度对列表进行排序,然后如果长度相同,我希望将那些相同长度的项目按其长度进行排序(就地)价值观。但我的实现无法正常工作。谁能看到我做错了什么吗?
我的结果是:
a b = 3
a b c = 1
a b c = 1
a b = 2
a b = 1
我想要的结果是:
a b c = 1
a b c = 1
a b = 3
a b = 2
a b = 1
I am trying to override comparable thusly:
public int compareTo(Object other) {
if(other.getlength() > this.getlength()){
return 1;
} else if (other.getlength() < this.getlength()){
return -1;
} else {
if (other.getVal() > this.getVal()){
return 1;
} else {
return -1;
}
}
}
What I want to happen, is for the list to be sorted on the length first, then if the length is the same, I want the those same lengthed items to be sorted (in place) on their values. But my implementation is not working correctly. Can anyone see what I am doing wrong?
My results are:
a b = 3
a b c = 1
a b c = 1
a b = 2
a b = 1
The results I want are:
a b c = 1
a b c = 1
a b = 3
a b = 2
a b = 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尽可能避免逻辑。说真的——在可行的情况下,使用算术来避免 if/else。它往往更可靠。在这种情况下:
Avoid logic where possible. Seriously - where feasible, use arithmetic to avoid if/else's. It tends to be more reliable. In this case:
从您的评论中不清楚列表是否已经排序。但是您可以通过在比较长度后对列表进行排序来处理这个问题。但是,您显然做错的事情是 object.getValue() ...这没有意义,您必须迭代两个列表并比较值以得出它们是否相等的结论。如果没有示例,这并不明显抱歉对于上述评论,您的比较器不可能得到此结果。你的逻辑在我看来是正确的。但最好也合并 w00t 的注释,否则您将有 a<'b 以及 a>b 并可能导致运行时错误。请检查比较器是否正确应用于您的排序功能(对象)。
it is not clear from your remarks that list would be already sorted or not. But you can handle that by sorting the list after comparing there lengths. But on thing which you are obviously doing wrong is object.getValue()...this doesnt makes sense you have to iterate through both lists and compare values to conclude if they are equal.It wasnt obvious without the example sorry for above comments, It is not possible to have this result with your comparator. Your logic looks correct to me. But it would be good idea to incorporate w00t's comments also otherwise you will have a<'b as well as a>b and could cause a runtime error. Please check if the comparator is applied properly to you sorting function ( objects ).