1

Say I have class A, which override the default equals method and implement Comparable interface (Comparable interface is said to be the natural ordering). To conform to good practice, the result returned by equals and Comparable's compareTo method should be consistent.

On some occasions, I want to compare instance of class A differently, so I implement Comparator interface (Comparator interface is said to be the unnatural ordering). So using Comparable's compareTo method and Comparator's compare method, the result would not be consistent.

If equals method and Comparable's compareTo interface is consistent, Comparable's comparaTo method and Comparator's compare method is not consistent, then equals method and Comparator's compare method would not be consistent as well.

So what are the consequences of equals method not consistent with Comparator's compare method, if there is any?

Thor
  • 9,638
  • 15
  • 62
  • 137
  • Use a `Comparator` instead - that way you don't have to care – MadProgrammer Apr 12 '18 at 01:31
  • @MadProgrammer could you please expand on that a little bit more? – Thor Apr 12 '18 at 01:32
  • It's recommended, but not strictly required that `Comparator.compare()` be consistent with `equals()`. – shmosel Apr 12 '18 at 01:33
  • @shmosel will there be any consequences if `Comparator.compare()` is not consistent with `equals()`? – Thor Apr 12 '18 at 01:34
  • There may be, depending on how it's used. See the [documentation](https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html) for details. – shmosel Apr 12 '18 at 01:37
  • @Thor remember to overwrite ``hashcode()`` as well when you were overwriting ``equals()`` as well :) – R.yan Apr 12 '18 at 01:56
  • @R.yan Thanks for the heads up! Definitely something I need to remember :) – Thor Apr 12 '18 at 02:02
  • `Comparator` allows you to define a "matching" algorithm which is independent of the `Object` itself, so you could have one which sorts `People` by name and one which sorts them by age and one which does both – MadProgrammer Apr 12 '18 at 02:26
  • If you're using a `Comparator` to implement a different order than the object's *natural order* (that is, its `Comparable.compareTo` method), you'd expect them to have different behaviors. Sure, they're not consistent with each other, but that's not a problem. Issues can arise if one of these comparison methods is not consistent with `equals`. For some examples of what can happen in this case, see my answer here: https://stackoverflow.com/a/53901802/1441122 – Stuart Marks Dec 23 '18 at 07:06

0 Answers0