老问题,但我今天需要这个,根据@iagreen的回答我已经概括了这个想法,也许它对某人有用......
public static class WeakValueHashMap<K,V> {
private HashMap<K,WeakReference<V>> mDatabase=new HashMap<K, WeakReference<V>>();
public V get(K key) {
WeakReference<V> weakRef=mDatabase.get(key);
if (weakRef==null) return null;
V result=weakRef.get();
if (result==null) {
// edge case where the key exists but the object has been garbage collected
// we remove the key from the table, because tables are slower the more
// keys they have (@kisp's comment)
mDatabase.remove(key);
}
return result;
}
public void put(K key, V value) {
mDatabase.put(key, new WeakReference<V>(value));
}
}
所以你可以做例如
private WeakValueHashMap<String,Drawable> mTextDrawables=new WeakValueHashMap<String,Drawable>();
并且可绘制对象将与Weakreferences
.
“containsValue”方法实现起来会比较棘手,你必须迭代和取消引用所有的 WeakRefs ...