Java Reference
In-Depth Information
Iterator keyIter = keys.iterator();
You can use the
iterator()
method for the object
keys
to iterate over all the keys in the map. Of
course, you can combine these two operations to get the iterator directly. For example:
Iterator keyIter = aMap.keySet().iterator(); // Get the iterator
while(keyIter.hasNext()) // Iterate over the keys
System.out.println((KeyType)keyIter.next());
This iterates over all the keys and outputs their
String
representation -
KeyType
in this fragment
represents the class type of the keys.
The method
entrySet()
returns a
Set
object referencing the key/object pairs. In a similar way to the
one that we used for the set of keys, you can obtain an iterator to make the
Map.Entry
objects
available. Each
Map.Entry
object will contain the following methods to operate on it:
Method
Description
getKey()
Returns the key for the
Map.Entry
object as type
Object
.
getValue()
Returns the object for the
Map.Entry
object as type
Object
.
setValue(Object new)
Sets the object for this
Map.Entry
object to the argument and
returns the original object. 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. This last exception does not apply to
HashMap
.
A
Map.Entry
object will also need an
equals()
method for comparisons with another
Map.Entry
object
passed as an argument and a
hashCode()
method to compute a hash code for the
Map.Entry
object.
With a set of
Map.Entry
objects you can obviously access the keys and the corresponding objects by
obtaining an iterator, and you can modify the object part of each key/object pair if you need to.
Finally the
values()
method for a
HashMap
object will return a
Collection
object that is a
collection of all the objects in the map. This enables you to use the
iterator()
member to obtain an
iterator for the collection of objects.