-1

Sorry for this duplicate question that has been already answered on other posts. Unfortunately i did not know how to implement it on my code :

public int compare(Group gp1, Group gp2){   
    if (gp1.isPredOf(gp2))
        return 1;
    if (gp2.isPredOf(gp1))
        return -1;
    return 0; 
}    

Note that if gp1 is a predecessor of gp2, gp2.isPredOf(gp1) will return false and vice versa.

Could you please show me the appropriate code to avoid this exception ?

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Comparison method violates its general contract!

Thank you for your help.

PS : the code of the function "isPredOf" :

 public boolean isPredOf(Group gp2){
  for (Operation op1 : this.operations){
        for (int i=0;i<=op1.job.operations.indexOf(op1);i++){
            if (gp2.operations.contains(op1.job.operations.get(i)))
                return true;
            }
    }

    return false;
}                             
  • 2
    Post the code of `isPredOf` method (or a simplified version of it) – Tunaki Oct 14 '15 at 13:51
  • It would also be useful to know if you've implemented `hashCode` and `equals` in your `Group` class? – hugh Oct 14 '15 at 13:57
  • This is the code of the function "isPredOf" `code` public boolean isPredOf(Group gp2){ for (Operation op1 : this.operations){ for (int i=0;i<=op1.job.operations.indexOf(op1);i++){ if (gp2.operations.contains(op1.job.operations.get(i))) return true; } } return false; }`code` – user1183836 Oct 14 '15 at 14:14

1 Answers1

0

Your isPredOf probably is not respecting transitivity. Check for null arguments they may creates this kind of problems.

The official documentation(http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html) says :

 The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y. (This implies that compare(x, y) must throw an exception if and only if compare(y, x) throws an exception.)

The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.

Finally, the implementor must ensure that compare(x, y)==0 implies that sgn(compare(x, z))==sgn(compare(y, z)) for all z.
Filippo Fratoni
  • 379
  • 2
  • 7