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(, ); map.put(, ); map.put(, ); // 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(, ); // 1 // Remove an entry from the map and return the value of the removed entry oldValue = map.remove(); // 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(, ); map.put(, ); map.put(, ); map.put(, ); // 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 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.
// Create the weak map Map weakMap = new WeakHashMap(); // Add a key to the weak map weakMap.put(, ); // Get all keys that are still being referenced Iterator it = weakMap.keySet().iterator(); while (it.hasNext()) { // Get key Object key = it.next(); }
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
WeakReference
object:
WeakReference weakValue = new WeakReference(); weakMap.put(, 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(); } }