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(); }
Creating a Map That Retains Order-of-Insertion
Map map = new LinkedHashMap(); // Add some elements map.put("1", "value1"); map.put("2", "value2"); map.put("3", "value3"); map.put("2", "value4"); // List the entries for (Iterator it=map.keySet().iterator(); it.hasNext(); ) { Object key = it.next(); Object value = map.get(key); } // [1=value1, 2=value4, 3=value3]
Automatically Removing an Unreferenced Element from a Hash TableWhen a key is added to a map, the map will prevent the key from being garbage-collected. However, a weak map will automatically remove a key if the key is not being referenced by any other object. An example where this type of map might be useful is a registry where a registrant is automatically removed after it is garbage-collected.The weak map does not automatically release the value if it is no longer used. To enable automatically release of the value, the value must be wrapped in a
// Create the weak map Map weakMap = new WeakHashMap(); // Add a key to the weak map weakMap.put(keyObject, valueObject); // Get all keys that are still being referenced Iterator it = weakMap.keySet().iterator(); while (it.hasNext()) { // Get key Object key = it.next(); }WeakReference
object:WeakReference weakValue = new WeakReference(valueObject); weakMap.put(keyObject, weakValue); // Get all keys that are still being referenced and check whether // or not the value has been garbage-collected it = weakMap.keySet().iterator(); while (it.hasNext()) { // Get key Object key = it.next(); weakValue = (WeakReference)weakMap.get(key); if (weakValue == null) { // Value has been garbage-collected } else { // Get value valueObject = weakValue.get(); } }