"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 this object withobj
, which is of type T. Return a negative integer, zero, or a positive integer, when this object is less than, equal, or greater thanobj
.
In the above, T
stands for the type of the objects.
For example, 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 |
StringA is regarded as less than StringB if StringA would be proceed StringB in a dictionary. For example,
Expression | Evaluates to |
---|---|
"apple".compareTo("orange") | Negative Integer |
"apple".compareTo("plum") | Negative Integer |
"apple".compareTo("apple") | Zero |
"orange".compareTo("orange") | Zero |
"orange".compareTo("apple") | Positive Integer |
Only the sign of the returned integer matters if the return value is not zero. The magnitude of a returned integer does not signify anything.
Examine the following:
String myPet = "Fido" ; String stray = "Rex" ; if ( myPet.compareTo( stray ) < 0 ) System.out.println( "Good Dog" ); else System.out.println( "Bad Dog" );
What is printed?