To enable automatically release of the value, the value must be wrapped in a WeakReference object : WeakHashMap « Collections « Java Tutorial






import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.Map;
import java.util.WeakHashMap;

public class Main {
  public static void main(String[] argv) throws Exception {
    Object keyObject = "";
    Object valueObject = "";
    Map weakMap = new WeakHashMap();

    weakMap.put(keyObject, valueObject);
    WeakReference weakValue = new WeakReference(valueObject);

    weakMap.put(keyObject, weakValue);

    Iterator it = weakMap.keySet().iterator();
    while (it.hasNext()) {
      Object key = it.next();
      weakValue = (WeakReference) weakMap.get(key);
      if (weakValue == null) {
        System.out.println("Value has been garbage-collected");
      } else {
        System.out.println("Get value");
        valueObject = weakValue.get();
      }
    }
  }
}








9.31.WeakHashMap
9.31.1.WeakHashMap Class
9.31.2.Understanding Weak References
9.31.3.Demonstrating the WeakHashMap
9.31.4.Create a WeakHashMap with a single element in it
9.31.5.To enable automatically release of the value, the value must be wrapped in a WeakReference object
9.31.6.Implements a combination of WeakHashMap and IdentityHashMap