Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
ASortedMap
is aMap
that maintains its entries in ascending order, sorted according to the keys' natural order, or according to aComparator
provided atSortedMap
creation time. Natural order andComparator
s are discussed in the section Object Ordering. TheMap
interface provides operations for the normalMap
operations 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(); }Map
analog ofSortedSet
.
The operations thatSortedMap
inherits fromMap
behave identically on sorted maps and normal maps with two exceptions:Although it isn't guaranteed by the interface, the
- The
Iterator
returned by theiterator
operation on any of the sorted map'sCollection
views traverse the collections in order.- The arrays returned by the
Collection
views'toArray
operations contain the keys, values, or entries in order.toString
method of theCollection
views in all the Java platform'sSortedMap
implementations returns a string containing all the elements of the view, in order.
By convention, all general-purposeMap
implementations provide a standard conversion constructor that takes aMap
;SortedMap
implementations 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 specifiedMap
instance were aSortedMap
, and if so, to sort the new map according to the same criterion (comparator or natural ordering). BecauseTreeMap
took the approach that it did, it also provides a constructor that takes aSortedMap
and returns a newTreeMap
containing 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 theSortedMap
constructor is invoked in preference to the ordinarymap
constructor.
SortedMap
implementations also provide by convention a constructor that takes aComparator
and returns an empty map sorted according to the specifiedComparator
. Ifnull
is passed to this constructor, it returns a set that sorts its mappings according to their keys' natural order.
Because this interface is a precisemap
analog ofSortedSet
, all the idioms and code examples in the section The SortedSet Interface apply toSortedMap
with only trivial modifications.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.