Java Reference
In-Depth Information
gaining
mainly
And this is all as it should be.
On the other hand, you may be writing a class and want to build in the comparison function-
ality so that you don't always have to remember to pass the
Comparator
with it. In this case,
you can directly implement the
java.lang.Comparable
interface. The
String
class; the
wrapper classes
Byte
,
Character
,
Double
,
Float
,
Long
,
Short
, and
Integer
,
BigInteger
,
and
BigDecimal
from
java.math
;
File
from
java.io
;
java.util.Date
; and
java.text.CollationKey
all implement this interface, so arrays or
Collections
of these
types can be sorted without providing a
Comparator
. Classes that implement
Comparable
are said to have a “natural” ordering. The documentation strongly recommends that a class's
natural ordering be consistent with its
equals()
method, and it is consistent with
equals()
if and only if
e1.compareTo((Object)e2)==0
has the same Boolean value as
e1.equals((Object)e2)
for every instance,
e1
and
e2
of the given class. This means that if
you implement
Comparable
, you should also implement
equals()
, and the logic of
equals()
should be consistent with the logic of the
compareTo()
method. Here, for ex-
ample, is part of the appointment class
Appt
from a hypothetical scheduling program:
// public class Appt implements Comparable {
// Much code and variables omitted - see online version
//-----------------------------------------------------------------
// METHODS - COMPARISON
//-----------------------------------------------------------------
/** compareTo method, from Comparable interface.
* Compare this Appointment against another, for purposes of sorting.
* <P>Only text, and date and time participate, not repetition!
* (Repetition has to do with recurring events, e.g.,
* "Meeting every Tuesday at 9").
* This methods is consistent with equals().
* @return -1 if this<a2, +1 if this>a2, else 0.
*/
@Override
public
public
int
int
compareTo
(
Appt a2
) {
iif
(
year
<
a2
.
year
)
return
return
-
1
;
iif
(
year
>
a2
.
year
)
return
return
+
1
;
iif
(
month
<
a2
.
month
)
return
return
-
1
;