The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util  [50 examples] > Hash Tables  [3 examples]

e355. Creating a Hash Table

A hash table, or map, holds key/value pairs.
    // Create a hash table
    Map map = new HashMap();    // hash table
    map = new TreeMap();        // sorted map
    
    // Add key/value pairs to the map
    map.put("a", new Integer(1));
    map.put("b", new Integer(2));
    map.put("c", new Integer(3));
    
    // Get number of entries in map
    int size = map.size();        // 2
    
    // Adding an entry whose key exists in the map causes
    // the new value to replace the old value
    Object oldValue = map.put("a", new Integer(9));  // 1
    
    // Remove an entry from the map and return the value of the removed entry
    oldValue = map.remove("c");  // 3
    
    // Iterate over the keys in the map
    Iterator it = map.keySet().iterator();
    while (it.hasNext()) {
        // Get key
        Object key = it.next();
    }
    
    // Iterate over the values in the map
    it = map.values().iterator();
    while (it.hasNext()) {
        // Get value
        Object value = it.next();
    }

 Related Examples
e356. Creating a Map That Retains Order-of-Insertion
e357. Automatically Removing an Unreferenced Element from a Hash Table

See also: Arrays    Bits    Collections    Dates    Lists    Property Files    Sets    Sorted Collections    Time    Timers   


© 2002 Addison-Wesley.