0

How to achieve always?

The compareTo method or compare method should be consistent with the equals method of the object being stored in TreeMap or TreeSet?

Maciej Lach
  • 1,622
  • 3
  • 20
  • 27
user2974606
  • 143
  • 1
  • 12
  • 1
    This is spelled out in [the documentation](http://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html). Maybe you can explain how you are having trouble with this. – Radiodef Oct 04 '14 at 21:40
  • While starting `int compareTo(T other) { if (equals(other)) return 0; if (null == other) ...` ensures `equals(other)` implies `0 == compareTo(other)`, there still might be cases where `0 == compareTo(other) = 0` but `!equals(other)`, necessitating `natural ordering inconsistent with equals` not only in the doc comment of `compareTo`, but of the class, also. Anyway, `equals(other)` implying `0 == compareTo(other)` might be irreconcilable with what you are trying to achieve in the first place. – greybeard Oct 04 '14 at 21:54

0 Answers0