Java Reference
In-Depth Information
compareTo() must be transitive :Foranynonnullreferencevalues x , y ,and
z , if x .compareTo( y ) > 0 is true, and if y .compareTo( z ) > 0 is
true, then x .compareTo( z ) > 0 must also be true.
Also, compareTo() shouldthrow NullPointerException whenthenullref-
erenceispassedtothismethod.However,youdonotneedtocheckfornullbecausethis
methodthrows NullPointerException whenitattemptstoaccessanullreferen-
ce's members.
Note Before Java 5 and its introduction of generics, compareTo() 's argument
was of type java.lang.Object and had to be cast to the appropriate type before
the comparison could be made. The cast operator would throw a
java.lang.ClassCastException instance when the argument's type was not
compatible with the cast.
You might occasionally need to store in a collection objects that are sorted in some
orderthatdiffersfromtheirnaturalordering.Inthiscase,youwouldsupplyacompar-
ator to provide that ordering.
A comparator is an object whose class implements the Comparator interface.
Thisinterface,whosegenerictypeis Comparator<T> ,providesthefollowingpairof
methods:
int compare(T o1, T o2) compares both arguments for order. This
methodreturns0when o1 equals o2 ,anegativevaluewhen o1 islessthan o2 ,
and a positive value when o1 is greater than o2 .
boolean equals(Object o) returns true when o “equals” this Com-
parator in that o is also a Comparator and imposes the same ordering.
Otherwise, this method returns false.
Note Comparator declares equals() becausethisinterfaceplacesanextracon-
dition on this method's contract. Additionally, this method can return true only if the
specified object is also a comparator and it imposes the same ordering as this com-
parator. Youdonothavetooverride Object 's equals() method,butdoingso may
improve performance by allowing programs to determine that two distinct comparators
impose the same order .
Chapter3 providedanexamplethatillustratedimplementing Comparable ,andyou
will discover another example later in this chapter. Also, this chapter will present ex-
amples of implementing Comparator .
Search WWH ::




Custom Search