Java Reference
In-Depth Information
String myKey = "Goofy";
Integer theObject = new Integer(12345);
if(aMap.put(myKey, theObject) != null)
System.out.println("Uh-oh, we bounced an object...");
Of course, you could throw your own exception here instead of displaying a message.
Note that the get() operation will return a reference to the object associated with the key, but it does
not remove it from the table. To retrieve an object and delete the entry containing it from the table, you
must use the remove() method. This accepts a key of type Object as an argument and returns the
object corresponding to the key:
theObject = (Integer)aMap.remove(theKey);
As was noted in the table, if there's no stored object corresponding to theKey or null was stored as
the object, null will be returned. Note how we have to explicitly cast the object returned from the hash
map to the correct class.
Processing all the Elements in a Map
The Map interface provides three ways of obtaining a collection view of the contents of a map. You can
obtain all the keys or all the key/object pairs from a Map object as an object of type Set . You can also
get a Collection object that references all the objects in the map. Note that the Set or Collection
object is essentially a view of the contents of a map, so changes to a HashMap object will be reflected in
the associated Set or Collection , and vice versa. The three methods involved are:
Method
Description
keySet()
Returns a Set object referencing the keys from the map.
entrySet()
Returns a Set object referencing the key/object pairs - each pair being an
object of type Map.Entry .
values()
Returns a Collection object referencing the objects stored in the map.
The type of the key/object pairs in the set returned by entrySet() looks a little unusual. The key/object
pairs are of type Map.Entry because Entry is an interface declared within the Map interface.
Let's first see how we can use a set of keys. The method keySet() for the HashMap class returns a
Set object referencing the set of keys that you can either use directly to access the keys or use indirectly
to get at the objects stored in the map. For a HashMap object aMap , you could get the set of all the keys
in the map with the statement:
Set keys = aMap.keySet();
Now you can get an iterator for this set of keys with the statement:
Search WWH ::




Custom Search