Mohan
Mohan

Reputation: 155

compare method violates its general contract exception java 7

Below code throws "Java Comparison method violates its general contract" when run on Java 6. But, on Java 7 it does not throw the same exception. what is the issue?. How can this code be modified to throw the exception on Java 7 as well?.

class ComparableScore implements Comparable<ComparableScore> {

    private int score;
    private String itemName;

    int getScore() {
        return score;
    }

    void setScore(int i) {
        score = i;
    }

    String getItemName() {
        return itemName;
    }

    void setItemName(String str) {
        itemName = str;
    }

    public int compareTo(ComparableScore 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 ComparableScore other = (ComparableScore) o;

        if (score == other.getScore()
                && this.getItemName().equalsIgnoreCase(other.getItemName()))
            return true;
        else
            return false;
    }
}

Upvotes: 0

Views: 1133

Answers (1)

Stephen C
Stephen C

Reputation: 719189

This relates to this Java "bug" - https://bugs.java.com/bugdatabase/view_bug?bug_id=7193557

Except it is not a bug, it is a feature. The new Java implementation of sort is telling you that your compareTo method is broken.

However, the bug report says that the exception is thrown on Java 7 not Java 6. And checking the Java 6 source code confirms this. That message doesn't appear in the source code for Arrays.sort which is where the sorting code is implemented in Java 6.


If your aim is to break your code in such a way that the exception occurs in Java 7, then:

  • The exception is not being thrown at the moment because the contract is not being broken. (Or at least, not in any obvious way that I can see ...)

  • I don't know the precise conditions that will trigger the exception.

  • Try some experiments (i.e. with different implementations of compareTo and equals that break the contract in different ways) or read the Java 7 source code to figure out for yourself what would cause it ... reproducibly.

  • (And why, why, why would you want to do that???)

Upvotes: 1

Related Questions