The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Collections
Lesson: Interfaces

The SortedMap Interface

A SortedMap (in the API reference documentation) is a Map (in the API reference documentation) that maintains its entries in ascending order, sorted according to the keys' natural order, or according to a Comparator provided at SortedMap creation time. Natural order and Comparators are discussed in the section Object Ordering (in the Collections trail). The Map interface provides operations for the normal Map operations and for:
public interface SortedMap<K, V> extends Map<K, V>{
    Comparator<? super K>comparator();
    SortedMap<K, V> subMap(K fromKey, K toKey);
    SortedMap<K, V> headMap(K toKey);
    SortedMap<K, V> tailMap(K fromKey);
    K firstKey();
    K lastKey();
}
This interface is the Map analog of SortedSet (in the API reference documentation).

Map Operations

The operations that SortedMap inherits from Map behave identically on sorted maps and normal maps with two exceptions: Although it isn't guaranteed by the interface, the toString method of the Collection views in all the Java platform's SortedMap implementations returns a string containing all the elements of the view, in order.

Standard Constructors

By convention, all general-purpose Map implementations provide a standard conversion constructor that takes a Map; SortedMap implementations are no exception. In TreeMap, this constructor creates an instance that orders its entries according to their keys' natural order. This was probably a mistake. It would have been better to check dynamically if the specified Map instance were a SortedMap, and if so, to sort the new map according to the same criterion (comparator or natural ordering). Because TreeMap took the approach that it did, it also provides a constructor that takes a SortedMap and returns a new TreeMap containing the same mappings as the given SortedMap, sorted according to the same criterion. Note that it is the compile-time type of the argument, not its runtime type, that determines whether the SortedMap constructor is invoked in preference to the ordinary map constructor.

SortedMap implementations also provide by convention a constructor that takes a Comparator and returns an empty map sorted according to the specified Comparator. If null is passed to this constructor, it returns a set that sorts its mappings according to their keys' natural order.

Comparison to SortedSet

Because this interface is a precise map analog of SortedSet, all the idioms and code examples in the section The SortedSet Interface (in the Collections trail) apply to SortedMap with only trivial modifications.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.