我的排序方法出现错误。
Comparison method violates its general contract
这是我使用排序方法的排序对象
public abstract class ComparablePerson extends IDValueItem implements
Comparable<ComparablePerson> {
private int score;
private String itemID,itemName;
//setters and getters
public int compareTo(ComparablePerson another) {
if (score == another.getScore())
return this.getItemName().compareToIgnoreCase(another.getItemName());
else if ((score) > another.getScore())
return 1;
else
return -1;
}
@Override
public boolean equals(Object o) {
final ComparablePerson other = (ComparablePerson) o;
if (score == other.getScore() && this.getItemName().equalsIgnoreCase(other.getItemName()))
return true;
else
return false;
}
我只是打电话 Collections.sort(ComparablePersonCollection);
这可能是什么原因造成的?
最佳答案
compareTo
和equals
方法实现似乎不一致,错误告诉您对于相同的两个对象 equals
给出 true while compareTo
不产生零,这是不正确的。我建议您调用compareTo
来自equals
确保一致性或以其他方式定义自定义 Comparator<T>
.
简单地做:
public abstract class ComparablePerson extends IDValueItem implements Comparable<ComparablePerson> {
private int score;
private String itemID,itemName;
//setters and getters
public int compareTo(ComparablePerson another) {
if (score == another.getScore())
return this.getItemName().compareToIgnoreCase(another.getItemName());
else if ((score) > another.getScore())
return 1;
else
return -1;
}
@Override
public boolean equals(Object o) {
return compareTo(o) == 0;
}
}
关于java - 比较方法违反了排序方法中的一般契约,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13763604/