Java Reference
In-Depth Information
C
OMMON
E
RROR
14.1: The
compareTo
Method Can
Return Any Integer, Not
JustÉČÉ1, 0, and 1
The
call a.compareTo(b)
is allowed to return any negative integer to
denote that
a
should come before
b
, not necessarily the valueɨ1. That is, the test
if (a.compareTo(b) == -1) // ERROR!
is generally wrong. Instead, you should test
if (a.compareTo(b) < 0) // OK
Why would a
compareTo
method ever want to return a number other thanɨ1, 0,
or 1 ? Sometimes, it is convenient to just return the difference of two integers. For
example, the
compareTo
method of the
Stri ng class
compares characters
in matching positions:
char c1 = charAt(i);
char c2 = other.charAt(i);
If the characters are different, then the method simply returns their difference:
if (c1 ! = c2) return c1 - c2;
This difference is a negative number if
c1
is less than
c2
, but it is not necessarily
the numberɨ1.
A
DVANCED
T
OPIC
14.4: The Parameterized
Comparable
Interface
As of Java version 5.0, the
Comparabl e
interface is a parameterized type,
similar to the
Array-List
type:
public interface Comparable
<T>
{
int compareTo(
T
other)
}