Java Reference
In-Depth Information
Thefollowingexampledeclaresamapof String keysand Color values,addssev-
eral entries to the map, and iterates over the keys and values:
Map<String, Color> colorMap = ...; // ... represents cre-
ation of a Map implementation
colorMap.put("red", Color.RED);
colorMap.put("blue", Color.BLUE);
colorMap.put("green", Color.GREEN);
colorMap.put("RED", Color.RED);
for (String colorKey: colorMap.keySet())
System.out.println(colorKey);
Collection<Color> colorValues = colorMap.values();
for
(Iterator<Color>
it
=
colorValues.iterator();
it.hasNext();)
System.out.println(it.next());
When running this example against a hashmap implementation (discussed later) of
colorMap , you should observe output similar to the following:
red
blue
green
RED
r = 255, g = 0, b = 0
r = 0, g = 0, b = 255
r = 0, g = 255, b = 0
r = 255, g = 0, b = 0
Thefirstfouroutputlinesidentifythemap'skeys;thesecondfouroutputlinesidenti-
fy the map's values.
The entrySet() methodreturnsa Set of Map.Entry objects.Eachoftheseob-
jectsdescribesasingleentryasakey/valuepairandisaninstanceofaclassthatimple-
mentsthe Map.Entry interface,where Entry isanestedinterfaceof Map . Table5-9
describes Map.Entry 's methods.
Search WWH ::




Custom Search