Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the compareTo method respect the general contract?

Chromosome contains a number of scores generated in different ways. The compareTo method actually tests the agreement of the methods and accordingly returns a result.

return 1: comp = -5..-1

return 0: comp = 0 (can happen in different scenarios one of which is that all scores are equal.

return -1: comp = 1..5

public int compareTo(Chromosome o) {
    if(o == null)
        return(1);
    int comp = 0;
    comp += Double.compare(getScore(1),o.getScore(1));
    comp += Double.compare(getScore(2),o.getScore(2));
    comp += Double.compare(getScore(3),o.getScore(3));
    comp += Double.compare(getScore(5),o.getScore(5));
    comp += Double.compare(getScore(7),o.getScore(7));
    if(comp == 0)
        return(0);
    if(comp > 0)
        return(1);
    else
        return(-1);
}

My question is, how to make this scenario adhere to the rules imposed by the contract for the comparator. Apparently it doesn't and I keep getting: java.lang.IllegalArgumentException: Comparison method violates its general contract!

like image 512
jallmer Avatar asked Jan 26 '26 04:01

jallmer


1 Answers

If you're implementing the Comparator interface then you need to use this method (given that your class is generic with the Chromosome tpye):

int compare(Chromosome o1, Chromosome o2)

However, it seems the more appropriate interface to implement in your case is Comparable. http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

int compareTo(Chromosome o)

Comparable is typically implemented to give instances of your class a natural ordering. Comparator is typically a separate class to what you're trying to compare, and can be used to give you several different types of orderings.

Regardless of what you're implementing, the class also needs to be typed:

class Chromosome implements Comparable<Chromosome> 

Otherwise the arguments should be Object, not Chromosome.

like image 98
zetches Avatar answered Jan 28 '26 21:01

zetches