Java Reference
In-Depth Information
requirement that you saw in
Section 14.8
for using the
sort
and
binarySearch
methods in the standard library.
To use a tree set, the elements must be comparable.
To use a
TreeMap
, the same requirement holds for the keys. There is no requirement
for the values.
For example, the
String
class implements the
Comparable
interface. The
compareTo
method compares strings in dictionary order. Thus, you can form tree
sets of strings, and use strings as keys for tree maps.
735
736
If the class of the tree set elements doesn't implement the
Comparable
interface, or
the sort order of the
compareTo
method isn't the one you want, then you can define
your own comparison by supplying a
Comparator
object to the
TreeSet
or
TreeMap
constructor. For example,
Comparator comp = new CoinComparator();
Set s = new TreeSet(comp);
As described in
Advanced Topic 14.5
, a
Comparator
object compares two
elements and returns a negative integer if the first is less than the second, zero if they
are identical, and a positive value otherwise. The example program at the end of this
section constructs a
TreeSet
of
Coin
objects, using the coin comparator of
Advanced Topic 14.5
.
ch16/treeset/TreeSetTester.java
1
import
java.util.Comparator;
2
import
java.util.Set;
3
import
java.util.TreeSet;
4
5 /**
6
A program to a test a tree set with a comparator for coins.
7 */
8
public class
TreeSetTester
9 {
10
public static void
main(String[] args)
11 {
12 Coin coin1 =
new
Coin(
0.25
,
ÐquarterÑ
);