Home > Java > javaTutorial > Why Does My Java `compareTo` Method Violate the General Contract?

Why Does My Java `compareTo` Method Violate the General Contract?

Susan Sarandon
Release: 2024-12-15 02:13:17
Original
807 people have browsed it

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;
}
Copy after login

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;
Copy after login

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!
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template