new WeakHashMap() : WeakReference « java.lang.ref « Java by API






new WeakHashMap()

  

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<Object, Object> weakMap = new WeakHashMap<Object, Object>();

    weakMap.put(keyObject, valueObject);
    WeakReference weakValue = new WeakReference<Object>(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();
      }
    }
  }
}

   
    
  








Related examples in the same category

1.new WeakReference(String referent, ReferenceQueue q)
2.new WeakReference(Object referent)
3.WeakReference: get()
4.WeakReference: isEnqueued()