Java error: “Comparison method violates its general contract!”

前端 未结 3 889
渐次进展
渐次进展 2020-12-10 13:52

I have this code:

package org.optimization.geneticAlgorithm;
import org.optimization.geneticAlgorithm.selection.Pair;

public abstract class Chromosome imple         


        
3条回答
  •  天涯浪人
    2020-12-10 14:09

    Most probably your fitness function is broken, in one of two ways:

    1. It doesn't always return the same value when called on the same object.
    2. It could return NaNs. Your compareTo() is not transitive in the presence of NaNs, as explained by Jon Skeet.

    You could rewrite your comparison function using Double.compare():

    public int compareTo(Chromosome o) {
        return Double.compare(o.fitness(), this.fitness());
    }
    

    This requires less code and takes care of corner cases (NaNs, the negative zero etc). Of course, whether these corner cases should be arising in the first place is for you to decide and address.

提交回复
热议问题