|      | Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form | 
 
ASortedMapis a
Mapthat maintains its entries in ascending order, sorted according to the keys' natural order, or according to a
Comparatorprovided at the time of theSortedMapcreation. Natural order andComparators are discussed in the Object Orderingsection. The
Mapinterface provides operations for normalMapoperations and for the following:The following interface is the
Range view performs arbitrary range operations on the sorted map
Endpoints returns the first or the last key in the sorted map
Comparator access returns theComparator, if any, used to sort the mapMapanalog ofSortedSet.
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(); }
The operationsSortedMapinherits fromMapbehave identically on sorted maps and normal maps with two exceptions:Although it isn't guaranteed by the interface, the
- The
Iteratorreturned by theiteratoroperation on any of the sorted map'sCollectionviews traverse the collections in order.- The arrays returned by the
Collectionviews'toArrayoperations contain the keys, values, or entries in order.toStringmethod of theCollectionviews in all the Java platform'sSortedMapimplementations returns a string containing all the elements of the view, in order.
By convention, all general-purposeMapimplementations provide a standard conversion constructor that takes aMap;SortedMapimplementations are no exception. InTreeMap, 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 to see whether the specifiedMapinstance was aSortedMap, and if so, to sort the new map according to the same criterion (comparator or natural ordering). BecauseTreeMaptook the approach it did, it also provides a constructor that takes aSortedMapand returns a newTreeMapcontaining the same mappings as the givenSortedMap, sorted according to the same criterion. Note that it is the compile-time type of the argument, not its runtime type, that determines whether theSortedMapconstructor is invoked in preference to the ordinarymapconstructor.
SortedMapimplementations also provide, by convention, a constructor that takes aComparatorand returns an empty map sorted according to the specifiedComparator. Ifnullis passed to this constructor, it returns aSetthat sorts its mappings according to their keys' natural order.
Because this interface is a precisemapanalog ofSortedSet, all the idioms and code examples in The SortedSet Interfacesection apply to
SortedMapwith only trivial modifications.
 
|      | Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form | 
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.