Home >Java >javaTutorial >Why Does My Java `compareTo` Method Violate the General Contract?
Error: Java's compareTo Method Violates General Contract
Encountering the "Comparison method violates its general contract" error can be frustrating. Despite extensive research, many developers struggle to resolve this issue.
This error occurs when the compareTo method, used for comparing objects in Java, violates the requirement of transitivity. Transitivity dictates that if A is greater than B and B is greater than C, then A must be greater than C.
In the provided code snippet, a custom comparator for CollectionItems was implemented but contained errors that led to the violation of transitivity.
Error 1:
if (card1.getRarity() < card2.getRarity()) { return 1; }
Here, if card1.getRarity() is greater than card2.getRarity(), the correct return value should be -1, not 1.
Error 2:
if (card1.getId() == card2.getId()) { //... } return -1;
When the IDs are not equal, the correct return value should be -1 if card1.getId() is smaller than card2.getId(), or 1 if card1.getId() is greater.
Revised Comparator:
To resolve these errors, here is a modified version of the comparator that adheres to transitivity:
if (card1.getSet() > card2.getSet()) { return 1; } if (card1.getSet() < card2.getSet()) { return -1; }; if (card1.getRarity() < card2.getRarity()) { return 1; } if (card1.getRarity() > card2.getRarity()) { return -1; } if (card1.getId() > card2.getId()) { return 1; } if (card1.getId() < card2.getId()) { return -1; } return cardType - item.getCardType(); //watch out for overflow!
The above is the detailed content of Why Does My Java `compareTo` Method Violate the General Contract?. For more information, please follow other related articles on the PHP Chinese website!