Weak hashmap with weak references to the values?

被刻印的时光 ゝ 提交于 2019-12-05 03:45:31

Pretty much what you said -- make the Bitmap (object side of the map) a WeakReference instead of a Bitmap. Then you have to add an extra check to see if the reference is still valid before passing it back to your entities. Here is a quick sketch of the general idea.

public class SingularBitmapFactory { 
    private HashMap <String, WeakReference<Bitmap>> cache = new HashMap<String, WeakReference<Bitmap>>();

    public Bitmap getBitmap(String key) {
        Bitmap image = null;
        WeakReference<Bitmap> ref = cache.get(key);
        if(ref != null) {
            image = ref.get();
        }
        if(image == null) {
            // Load image here ... 
            cache.put(key, new WeakReference<Bitmap>(image));
        }
        return image;   
    }
}

Old question, but I needed this today, and based on @iagreen's answer I've generalized the idea, maybe it comes in handy to someone ...

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));
    }
}

So you can just do for example

    private WeakValueHashMap<String,Drawable> mTextDrawables=new WeakValueHashMap<String,Drawable>();

and the Drawables would be stored with Weakreferences.

The method "containsValue" would be trickier to implement, you'd have to iterate and dereference all the WeakRefs ...

The best way is to use the WeakHashMap class which does all the work for you and doesn't require any changes in your code. There is a really good tutorial here: http://weblogs.java.net/blog/2006/05/04/understanding-weak-references Its rather oldish but still alright. It is important that the WeakHashMap stores a weak reference to the key. That means you can't just use a constant string value as the key but instead use something like a Integer and store it in a constants class as a weak reference.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!