Start of Tutorial > Start of Trail > Start of Lesson | Search |
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 on Object Ordering.) In addition to the normalMap
operations, theMap
interface provides operations for:
- Range-view: Performs arbitrary range operations on the sorted map.
- Endpoints: Returns the first or last key in the sorted map.
- Comparator access: Returns the
Comparator
used to sort the map (if any).This interface is thepublic interface SortedMap extends Map { Comparator comparator(); SortedMap subMap(Object fromKey, Object toKey); SortedMap headMap(Object toKey); SortedMap tailMap(Object fromKey); Object first(); Object last(); }Map
analogue 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 the sorted map'sCollection
-views traverse the collections in order.- The arrays returned by the
Collection
-views'toArray
operations contains the keys, values, or entries in order.toString
method of theCollection
-views in all the JDK'sSortedMap
implementations returns a string containing all the elements of the view, in order.
By convention, allMap
implementations provide a standard constructor that takes aMap
, andSortedMap
implementations are no exception. This constructor creates aSortedMap
object that orders its entries according to their keys' natural order. Additionally, by convention,SortedMap
implementations provide two other standard constructors:The first of these standard constructors is the normal way to create an empty
- One that takes a
Comparator
and returns a new (empty)SortedMap
sorted according to the specifiedComparator
.- One that takes a
SortedMap
and returns a newSortedMap
containing the same mappings as the givenSortedMap
, and sorted according to the sameComparator
(or using the elements' natural ordering, if the specifiedSortedMap
did too). Note that it is the compile-time type of the argument that determines whether this constructor is invoked in preference to the ordinaryMap
constructor, and not its runtime type!SortedMap
with an explicitComparator
. The second is similar in spirit to the standardMap
constructor: It creates a copy of aSortedMap
with the same ordering, but with a programmer specified implementation type.
Because this interface is a preciseMap
analogue ofSortedSet
, all of the idioms and code examples in theSortedSet
section apply toSortedMap
, with only trivial modifications.
Start of Tutorial > Start of Trail | Search |