Comparable Interface
Objects that have an ordering are compared using the compareTo() method.
2. Comparable <T> Interface
Answer:
"apple", "orange", "plum".
This is the order that compareTo()
would place the strings.
Comparable<T>
Interface
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 |
T
stands for the type of the objects. If the objects are String
s, then T
is String
. String
s implement the Comparable<String>
interface.
If an object is of a class that implements Comparable
, then that object is less than, equal, 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 than, equal, or greater
than is this enough to put a collection of objects in order?