THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1
public SortedMap<K,V>tailMap(K minKey)

Returns a view of the portion of the map whose keys are greater than or equal
to minKey.

Any returned map is backed by the original map so changes made to either are visible to the other.


A SortedMap is to Map what SortedSet is to Set and provides almost identical functionality except that
SortedMap works with keys. The exceptions thrown by the SortedMap methods mirror those thrown by
its SortedSet counterparts.


The java.util package gives you four general-purpose Map implementationsHashMap,
LinkedHashMap, IdentityHashMap, and WeakHashMapand one SortedMap implementation,
TReeMap.


21.8.1. HashMap


HashMap implements Map with a hashtable, where each key's hashCode method is used to pick a place in
the table. With a well-written hashCode method, adding, removing, or finding a key/value pair is 0(1). This
makes a HashMap a very efficient way to associate a key with a valueHashMap is one of the most
commonly used collections. You already have seen a HashMap in "Implementing Interfaces" on page 127.
The constructors for HashMap are


publicHashMap(int initialCapacity, float loadFactor)

Creates a new HashMap with initialCapacity hash buckets and the
given loadFactor, which must be a positive number.

publicHashMap(int initialCapacity)

Creates a new HashMap with the given initialCapacity and a default
load factor.

publicHashMap()

Creates a new HashMap with default initial capacity and load factor.

publicHashMap(Map<? extends K,? extends V> map)

Creates a new HashMap whose initial mappings are copied from map. The
initial capacity is based on the size of map; the default load factor is used.

The internal table used by a hash map consists of a number of buckets, initially determined by the initial
capacity of the hash map. The hash code of an object (or a special hashing function used by the hash map
implementation) determines which bucket an object should be stored in. The fewer the number of buckets, the
more likely that different objects will get stored in the same bucket, so looking up the object will take longer
because the bucket has to be examined in detail. The more buckets there are, the less likely it is that this will
occur, and the lookup performance will improvebut the space occupied by the hash map will increase. Further,
the more buckets there are, the longer iteration will take, so if iteration is important you may want to reduce
the number of bucketsthe cost of iteration is proportional to the sum of the hash map's size and capacity. The
load factor determines when the hash map will automatically have its capacity increased. When the number of
entries in the hash map exceeds the product of the load factor and the current capacity, the capacity will be
doubled. Increasing the capacity requires that all the elements be rehashed and stored in the correct new

Free download pdf