Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

usekeySet( ). To get a collection-view of the values, usevalues( ). Collection-views are the
means by which maps are integrated into the larger Collections Framework.


The SortedMap Interface
TheSortedMapinterface extendsMap. It ensures that the entries are maintained in ascending
order based on the keys.SortedMapis generic and is declared as shown here:


interface SortedMap<K, V>

Here,Kspecifies the type of keys, andVspecifies the type of values.
The methods declared bySortedMapare summarized in Table 17-11. Several methods throw
aNoSuchElementExceptionwhen no items are in the invoking map. AClassCastException
is thrown when an object is incompatible with the elements in a map. ANullPointerException
is thrown if an attempt is made to use anullobject whennullis not allowed in the map. An
IllegalArgumentExceptionis thrown if an invalid argument is used.
Sorted maps allow very efficient manipulations ofsubmaps(in other words, subsets of a
map). To obtain a submap, useheadMap( ),tailMap( ), orsubMap( ). To get the first key in
the set, callfirstKey( ). To get the last key, uselastKey( ).


Chapter 17: java.util Part 1: The Collections Framework 465


Method Description
void clear( ) Removes all key/value pairs from the invoking map.
boolean containsKey(Objectk) Returnstrueif the invoking map containskas a key. Other wise,
returnsfalse.
boolean containsValue(Objectv) Returnstrueif the map containsvas a value. Other wise, returnsfalse.
Set<Map.Entr y<K, V>> entr ySet( ) Returns aSetthat contains the entries in the map. The set contains
objects of typeMap.Entry. Thus, this method provides a set-view of the
invoking map.
boolean equals(Objectobj) Returnstrueifobjis aMapand contains the same entries. Other wise,
returnsfalse.
V get(Objectk) Returns the value associated with the keyk.Returnsnullif the key is
not found.
int hashCode( ) Returns the hash code for the invoking map.
boolean isEmpty( ) Returnstrueif the invoking map is empty. Other wise, returnsfalse.
Set<K> keySet( ) Returns aSetthat contains the keys in the invoking map. This method
provides a set-view of the keys in the invoking map.
V put(Kk, Vv) Puts an entr y in the invoking map, over writing any previous value
associated with the key. The key and value arekandv,respectively.
Returnsnullif the key did not already exist. Other wise, the previous
value linked to the key is returned.
void putAll(Map<? extends K,
void putAll(Map<? extends V>m)

Puts all the entries fromminto this map.

V remove(Objectk) Removes the entr y whose key equalsk.
int size( ) Returns the number of key/value pairs in the map.
Collection<V> values( ) Returns a collection containing the values in the map. This method
provides a collection-view of the values in the map.

TABLE 17-10 The Methods Defined byMap

Free download pdf