Comparable Interface

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

2. Comparable <T> Interface


"apple", "orange", "plum".

This is the order that compareTo() would place the strings.

Comparable<T> Interface

An interface consists of constants and method declarations. The Comparable<T> interface consists of just one method (and no constants):

int compareTo( T obj )                        
Compare the object running obj, which
is of type T. Return a
negative integer, zero, or a
positive integer, when he
object running the method is
less than, equal, or greater
than obj.

T stands for the type of the objects. If the objects are Strings, then T is StringStrings implement the Comparable<String> interface.

If an object is of a class that implements Comparable, then that object is less thanequal, or greater than any object of that class. compareTo() returns an integer to show which of these three relations hold.

  Relation   objectA.compareTo( objectB )
objectA Less Than objectB Negative Integer
objectA Equal objectB Zero
objectA Greater Than objectB Positive Integer

Question 2:

Does compartTo() tell us enough?

If any two objects can be compared, and the result is less thanequal, or greater
 is this enough to put a collection of objects in order?