Java Reference
In-Depth Information
706
Figure 4
Map Classes and Interfaces in the Standard Library
Use the
put
method to add an association:
favoriteColors.put("Juliet", Color.PINK);
You can change the value of an existing association, simply by calling
put
again:
favoriteColors.put("Juliet", Color.RED);
The
get
method returns the value associated with a key.
Color julietsFavoriteColor =
favoriteColors.get("Juliet");
If you ask for a key that isn't associated with any values, then the
get
method returns
null
.
To remove a key and its associated value, use the
remove
method:
favoriteColors.remove("Juliet");
Sometimes you want to enumerate all keys in a map. The
keySet
method yields the
set of keys. You can then ask the key set for an iterator and get all keys. From each
key, you can find the associated value with the
get
method. Thus, the following
instructions print all key/value pairs in a map
m
:
Set<String> keySet = m.keySet();
for (String key : keySet)