Java Reference
In-Depth Information
The abstract data type
map
describes a collection that allows you to create one-
way associations between pairs of objects to solve these kinds of problems.
Map
A collection that associates objects called keys with objects called values.
Maps can be used to solve a surprisingly large number of problems. A map can
group all the words in a book by length and report how many words there are of each
length. Maps can associate chat users with their set of friends and buddies. Maps can
even represent a family tree associating each person with his or her mother and father.
A map associates
keys
with
values.
You can store a key/value pair into a map; later
in your code, if you supply just the key to the map, it will give you back the value
associated with that key. A key can map to only one value, but it's possible for multi-
ple keys to map to the same value. The Java Collections Framework includes an
interface called
Map
representing this ADT.
You can think of a map as a pair of connected collections: a set of keys and a col-
lection of values associated with those keys. Figure 11.4 is an example of this idea
that maps first names to last names.
The two primary classes that implement the
Map
interface are called
HashMap
and
TreeMap
. These class names parallel the ones used in the set collections, because the
maps and sets have similar internal implementations.
HashMap
is the more general-
purpose map; a
TreeMap
stores comparable keys in sorted order.
A
Map
is constructed with not one but two generic type parameters, separated by a
comma. The first type parameter represents the type of the keys, and the second rep-
resents the type of the values. The inclusion of two parameters makes the declaration
line in your code lengthy. The line of code that follows is an example of constructing
Keys
Values
Romeo
Montague
Tyler
Durden
Tybalt
Capulet
Juliet
Figure 11.4
Mapping keys (first names) to values (last names)
Search WWH ::
Custom Search