Rules for compareTo()

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.

Answer:

positive

Rules for compareTo()

With all objects, compareTo() works the way number comparisons work in ordinary arithmetic. Here are a few rules. Most of these are fairly clear if you think about numbers. Say that A, B, and C are Integers.

If A.compareTo(B) > 0 then B.compareTo(A) < 0.

If A.compareTo(B) > 0 and B.compareTo(C) > 0 then A.compareTo(C) > 0.

If A.compareTo(B) == 0 then A.compareTo(Z) and B.compareTo(Z) should give the same result, no matter what Z is.

The classes that come with Java follow these rules. If you write a class that implements Comparable, you need to follow these rules. This is not hard to do because most sensible compareTo() methods will do this naturally.

QUESTION 4:

Say that X.compareTo(Y)==0.

Is it then true that X.equals(Y)?