The TreeMap Class

TIle TrecMap class implements the Map interface by using a tree. A TreeMap provides an efficient means.of storing key value pairs in sorted order, and allows rapid retrieval. You should note that, unlike a hash map, a tree map guarantees that its .elements will be sorted in ascending key order.

The following TrecMap constructors are defined:

TreeMap( )
TreeMap(Comparator comp) .
TreeMap(Map 111)
TreeMap(SortedMap Sill)

The first form constructs an empty tree map that will be sorted by using the natural order of its keys. The second form constructs an empty tree-based map that will be sorted by using the Comparator couip, (Comparators arc discussed later in this chapter.) TIle third form initializes a tree map with the entries from Ill, which will be .sorted by using the natural order of the keys. The fourth. form initializes a tree map with the entries from Sill, which will be sorted in the same order as Sill. TreeMap implements SortcdMap and extends does nol define any additional methods of its own. . .

The following program reworks the preceding example so that it uses TreeMap: The following is the output from this.program:

Jane Baker: 1378.0
John Doe: 3434.34
Ralph Smith: ~19.08
Todd Hali: 99.22
Tom Smith: 123.22
John Doe'&1,- current balance :4434 ;34

Notice that TreeMap sorts the keys. However, in this case, they are sorted by first name instead of.last name. You can alter this behavior by specifying a comparator when th,e mnp is created. The next section describes how.

Share This