0

This is my code:

Collections.sort(ordered_neighborhood, (m1, m2) -> {
      double improvM1 = 0, improvM2 = 0, occurrM1 = 0, occurrM2 = 0;
      improvM1 = getImprovementsRate(moveStatsList, m1);
      improvM2 = getImprovementsRate(moveStatsList, m2);
      occurrM1 = getOccurrencesRate(moveStatsList, m1);
      occurrM2 = getOccurrencesRate(moveStatsList, m2);
      int costM1 = (int) (((m1.after - m1.before) - improvM1 + occurrM1) * 1000);
      int costM2 = (int) (((m2.after - m2.before) - improvM2 + occurrM2) * 1000);
      int r = (costM1 - costM2);
      return r;
    });

getImprovementsRate get an attribute from moveStatsList for m1 and m2 that doesn't change during comparison. The same for getOccurrencesRate

m1.after - m1.before = 0 makes m1 and m2 equals, but I would to weight m1 and m2 with two weights arrays.

I seen "Comparison method violates its general contract!" question but: the problem is that the error doesn't compare every time I run my programs. It seems to be non deterministic. Maybe casting from double to int?

GinoC
  • 442
  • 4
  • 16
  • Are you sure that you return `0` in each instance where `.equals` returns true? Also, you need to watch out for precision losses as you're casting `double` to `int`, which can cause otherwise different different objects to be treated as equal (or vice-versa) – ernest_k Feb 28 '18 at 17:23
  • I've not implemented `.equals` in `m1` and `m2` class, but I don't think that is the problem because error appear only sometimes. Maybe cast `double` to `int`. I'll try. – GinoC Feb 28 '18 at 17:44
  • @ErnestKiwele it's not *required* that `equals()` and `compareTo()` are consistent, it's just strongly recommended. The given exception is because `compareTo()` is [failing one of the 3 required cases.](https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html#compareTo-T-) – Kayaman Feb 28 '18 at 18:01
  • @Kayaman Thanks, I suppose your wording is more accurate; but... you know what I meant :-) – ernest_k Feb 28 '18 at 18:05

0 Answers0