弱哈希映射与该值弱引用?与该、弱哈希

2023-09-07 23:45:36 作者:蜀山掌门

我建立一个Android应用程序,其中每个实体都有一个位图重新presents的精灵。然而,每一个实体可以被复制(有可能是例如实体航空自卫队的3份)。

I am building an android app where each entity has a bitmap that represents its sprite. However, each entity can be be duplicated (there might be 3 copies of entity asdf for example).

一种方法是加载所有的精灵前期,然后把正确的精灵在实体的构造函数。

One approach is to load all the sprites upfront, and then put the correct sprite in the constructors of the entities.

不过,我要脱code懒洋洋的位图,从而使实体的构造函数将取消code中的位图。与此唯一的问题是重复的实体将加载相同的位图的两倍,采用2倍内存(或N次,如果创建实体n次)。

However, I want to decode the bitmaps lazily, so that the constructors of the entities will decode the bitmaps. The only problem with this is that duplicated entities will load the same bitmap twice, using 2x the memory (Or n times if the entity is created n times).

要解决这个问题,我建立了会去codeD位图存储到一个散列的SingularBitmapFactory,如果相同的位图被要求再次,将直接返回previously散列而不是建立一个新的一。带着这样的问题,不过,是该工厂拥有所有的位图的副本,所以永远不会得到垃圾回收。

To fix this, I built a SingularBitmapFactory that will store a decoded Bitmap into a hash, and if the same bitmap is asked for again, will simply return the previously hashed one instead of building a new one. Problem with this, though, is that the factory holds a copy of all bitmaps, and so won't ever get garbage collected.

什么是HashMap中切换一个与弱的参考价值的最佳方式?在otherwords,我想其中的值不会GC'd的结构是否有任何其他对象持有对它的引用,但只要没有其他对象引用它,那么它可以GC'd。

What's the best way to switch the hashmap to one with weakly referenced values? In otherwords, I want a structure where the values won't be GC'd if any other object holds a reference to it, but as long as no other objects refers it, then it can be GC'd.

推荐答案

pretty你说什么得多 - 使位图(地图的物体侧)的WeakReference一个,而不是一个位图。然后,你必须添加一个额外的检查,看是否引用仍然传递回你的实体之前有效。这里的总体思路速写。

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