Java Reference
In-Depth Information
Theframework's implementation classes alsoinclude theabstract
AbstractCol-
lection
,
AbstractList
,
AbstractSequentialList
,
AbstractSet
,
Ab-
stractQueue
,and
AbstractMap
classes.Theseclassesofferskeletalimplementa-
tions of the core interfaces to facilitate the creation of concrete implementation classes.
Finally, the framework provides two utility classes:
Arrays
and
Collections
.
Comparable Versus Comparator
Acollectionimplementationstoresitselementsinsome
order
(arrangement).Thisorder
maybeunsorted,oritmaybesortedaccordingtosomecriterion(suchasalphabetical,
numerical, or chronological).
Asortedcollectionimplementationdefaultstostoringitselementsaccordingtotheir
natural ordering
.Forexample,thenaturalorderingof
String
objectsis
lexicographic
or
dictionary
(also known as alphabetical) order.
Acollectioncannotrelyon
equals()
todictatenaturalorderingbecausethismeth-
odcanonlydetermineiftwoelementsareequivalent.Instead,elementclassesmustim-
plement the
java.lang.Comparable<T>
interface andits
int compareTo(T
o)
method.
Note
Accordingto
Comparable
'sJavadocumentation,thisinterfaceisconsidered
to be part of the Collections Framework, even though it is a member of the
java.lang
package.
A sorted collection uses
compareTo()
to determine the natural ordering of this
method's element argument
o
in a collection.
compareTo()
compares argument
o
with the current element (which is the element on which
compareTo()
was called)
and does the following:
• It returns a negative value when the current element should precede
o
.
• It returns a zero value when the current element and
o
are the same.
• It returns a positive value when the current element should succeed
o
.
When you need to implement
Comparable
's
compareTo()
method, there are
somerulesthatyoumustfollow.Theserules,listednext,aresimilartothoseshownin
•
compareTo()
must be reflexive
:Foranynonnullreferencevalue
x
,
x
.com-
pareTo(
x
)
must return 0.
•
compareTo()
must be symmetric
:Foranynonnullreferencevalues
x
and
y
,
x
.compareTo(
y
) == -y.compareTo(x)
must hold.