package java.util; import java.lang.ref.ReferenceQueue; import java.lang.ref.Reference; import java.lang.ref.WeakReference; public class WeakHashMap implements Map { private final HashMap map; private final ReferenceQueue queue; public WeakHashMap(int capacity) { map = new HashMap(capacity, new MyCellFactory()); queue = new ReferenceQueue(); } public WeakHashMap() { this(0); } private void poll() { for (MyCell c = (MyCell) queue.poll(); c != null; c = (MyCell) queue.poll()) { map.remove(c); } } public int size() { return map.size(); } public boolean containsKey(K key) { poll(); return map.containsKey(key); } public boolean containsValue(V value) { poll(); return map.containsValue(value); } public V get(K key) { poll(); return map.get(key); } public V put(K key, V value) { poll(); return map.put(key, value); } public V remove(K key) { poll(); return map.remove(key); } public void clear() { map.clear(); } public Set> entrySet() { return map.entrySet(); } public Set keySet() { return map.keySet(); } public Collection values() { return map.values(); } private static class MyCell extends WeakReference implements HashMap.Cell { public V value; public HashMap.Cell next; public int hashCode; public MyCell(K key, V value, HashMap.Cell next) { super(key); this.value = value; this.next = next; this.hashCode = (key == null ? 0 : key.hashCode()); } public K getKey() { return get(); } public V getValue() { return value; } public void setValue(V value) { this.value = value; } public HashMap.Cell next() { return next; } public void setNext(HashMap.Cell next) { this.next = next; } public int hashCode() { return hashCode; } } private static class MyCellFactory implements HashMap.CellFactory { public HashMap.Cell make(K key, V value, HashMap.Cell next) { return new MyCell(key, value, next); } } }