作为存储位图的LruCache中的键的类的实例

时间:2013-08-28 07:49:15

标签: java android

我想使用android LruCache在内存中存储位图,但我通过散列,宽度,高度来识别位图。所以我做了这样的事情:

class Key {
    private String hash;
    private int widht, height;
}

LruCache<Key, Bitmap> imagesCache = new LruCache<Key, Bitmap>(1024) {
 @Override
    protected int sizeOf(Key key, Bitmap value) {
        // TODO Auto-generated method stub
        return super.sizeOf(key, value);
    }
}

这是一种正确的方式,下一步是什么?

提前致谢。

2 个答案:

答案 0 :(得分:0)

您需要覆盖类中用作键的equalshashCode方法。确保它们一致,即当equals返回true时,hashCode也必须返回相同的值。

答案 1 :(得分:0)

所以我必须自己回答。我用Google搜索,然后在http://www.javaranch.com/journal/2002/10/equalhash.html找到了Equals and Hash Code文章,据此我做了类似的事情:

private class Key {
    public Key(String hash, int width, int height, boolean fill) {
        this.hash = hash;
        this.width = width;
        this.height = height;
    }

    @Override
    public int hashCode() {
        int hash = 7;

        hash = 31 * hash + this.width;
        hash = 31 * hash + this.height;

        return hash;
    }

    public boolean equals(Object obj) {

        if(this == obj)
            return true;

        if(obj == null || obj.getClass() != this.getClass())
            return false;

        return this.width == ((Key)obj).width && this.height 
               == ((Key)obj).height && (this.hash == ((Key)obj).hash || 
               (this.hash != null && this.hash.equals(((Key)obj).hash)));
    }

Mabey我会被某人使用。

相关问题