I get an error in my sorting method.
Comparison method violates its general contract
This is my sorting object with sort method
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;
}
I just call
Collections.sort(ComparablePersonCollection);
What can be the cause of this?
The
compareToandequalsmethod implementations seem to be inconsistent, the error is telling you that for the same two objectsequalsgives true whilecompareTodoes not produce zero, which is incorrect. I suggest you invokecompareTofromequalsto ensure consistency or otherwise define a customComparator<T>.Simply do: