|
|
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 atSortedMapcreation time. Natural order andComparators are discussed in the section Object Ordering. The
Mapinterface provides operations for the normalMapoperations and for:
- 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 the
Comparator, if any, used to sort the map.This interface is thepublic 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(); }Mapanalog ofSortedSet.
The operations thatSortedMapinherits 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 if the specifiedMapinstance were aSortedMap, and if so, to sort the new map according to the same criterion (comparator or natural ordering). BecauseTreeMaptook the approach that 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 a set that sorts its mappings according to their keys' natural order.
Because this interface is a precisemapanalog ofSortedSet, all the idioms and code examples in the section The SortedSet Interfaceapply 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.