Comparable Interface

Objects that have an ordering are compared using the compareTo() method.

6. Rules for compareTo()


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 sensible if you think about numbers. Say that AB, and C are Integers.

compareNumbers01

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

compareNumbers02

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

compareNumbers03

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 6:

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

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