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

只愿长相守 提交于 2019-11-28 12:03:51

You could get into that situation if you have any NaN values:

For example:

public class Test
{
    public static void main(String[] args) {
        double a = Double.NaN;
        double b = Double.NaN;
        double c = 5;

        System.out.println(a < b);
        System.out.println(a > b);
        System.out.println(b < c);
        System.out.println(c < b);
    }
}

All of these print false. So you could end up in a situation where two non-NaN values were both deemed "equal" to NaN, but one was greater than the other. Basically, you should work out how you want to handle NaN values. Also check that that really is the problem, of course... do you really want NaN values for your fitness?

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.

You should try adding if (this == o) return 0; Because the same object must be returned equal.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!