JavaAdvanced#collections#oop

What is the difference between the Comparable interface's compareTo() contract and a poorly implemented one?

compareTo() must be consistent, transitive, and (ideally) consistent with equals() — a.compareTo(b) should have the opposite sign of b.compareTo(a). Breaking this contract causes unpredictable behavior in sorted collections like TreeSet or TreeMap.

Example
class BadPoint implements Comparable<BadPoint> {
  int x;
  public int compareTo(BadPoint o) { return x > o.x ? 1 : 0; } // broken: never returns negative, violates contract
}

Related Questions

1
JavaBeginner#jvm#fundamentals

What is JVM?

Open
2
JavaBeginner#jvm#jdk

Difference between JDK, JRE and JVM?

Open
3
JavaBeginner#operators#object

What is the difference between == and equals() in Java?

Open