- Maps associate the data elements in the collection with keys. The keys are derived from type Object, and may be different a type than the data. The get and put methods provide access to elements at a particular key.
Map userAges = new HashMap();
ages.put("John", new Integer(25));
ages.put("Nicole", new Integer(32));
ages.put("Bob", new Integer(43));
// How old is Bob?
Integer bobsAge = (Integer)userAges.get("Bob");
// if we have a user named Nicole, what's her age?
if(userAges.containsKey("Nicole"))
{
Integer nicolesAge = (Integer)userAges.get("Nicole");
}
- Caution: If the key object is mutable, take care not to change its value after using it in a Map.
- There are several Map implementations including HashMap and Hashtable.
- As a Java 1.1 legacy class, Hashtable is syncronized for thread safety.
Next: Collection Utilities
Up: Collections framework
Previous: Lists
  Contents
|