Java Reference
In-Depth Information
for(String key : aMap.keySet()) {
System.out.println(key);
}
That's much neater than messing about with an iterator, isn't it? In general, the collection-based for loop
provides you with code that is easier to understand than an iterator.
Of course, you could use the keys to extract the values but the Collection<> object that is returned by the
values() method provides you with a more direct way of doing this. Here's how you could list the values
stored in aMap , assuming it is of type HashMap<String,Integer> :
Collection<Integer> collection = aMap.values();
for(Integer i : collection) {
System.out.println(i);
}
This uses a collection-based for loop to iterate over the elements in the collection of values that the val-
ues() method returns.
The entrySet() method returns a Set<Map.Entry<K,V>> object containing the key/object pairs. In a
similar way to that used for the set of keys, you use a for loop to access the Map.Entry<> objects. Each
Map.Entry<K,V> object contains the following methods:
K getKey() : Returns the key for the Map.Entry<K,V> object.
V getValue() : Returns the value for the Map.Entry<K,V> object.
V setValue(V new) : Sets the value for this Map.Entry<K,V> object to the argument and returns
the original value. Remember that this alters the original map. This method throws:
UnsupportedOperationException if put() is not supported by the underlying map.
ClassCastException if the argument cannot be stored because of its type.
IllegalArgumentException if the argument is otherwise invalid.
NullPointerException if the map does not allow null objects to be stored and the ar-
gument is null . This last exception does not apply to HashMap<> .
A Map.Entry<> object also needs an equals() method for comparisons with another Map.Entry<> ob-
ject passed as an argument and a hashCode() method to compute a hashcode for the Map.Entry object.
With a set of Map.Entry<> objects you can obviously access the keys and the corresponding values using a
collection-based for loop, and you can modify the value part of each key/value pair if you need to.
You have waded through a lot of the theory for HashMap<> objects; let's put together an example that
applies it.
You can create a very simple phone book that uses a map. We won't worry too much about error recovery
so as not to bulk up the code. You'll use a variation of the last version of the Person class that you saw
earlier in this chapter in the example where you were sorting objects in a vector. Copy the source file to a
new directory called TryPhoneBook or something similar. Besides the Person class, you need to create a
PhoneNumber class and a BookEntry class that represents an entry in your phone book combining a name
and a number. You could add other stuff such as the address, but this is not necessary to show the principles.
You'll also define a PhoneBook class to represent the phone book.
Search WWH ::




Custom Search