我阅读了一些使用LruCache来实现存储位图图像的缓存机制的示例。但是看了文档http://developer.android.com/reference/android/util/LruCache.html还是不知道怎么用为了它。
例如,在文档中,它提到“以用户定义的单位返回键和值的条目大小”。在 sizeof() 中。条目的大小是什么意思?这是否意味着它允许的条目数,例如 return 10 将允许我拥有 10 个缓存对象引用。
public class LruBitmapCache extends LruCache<String, Bitmap> implements
ImageCache {
public static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
return cacheSize;
}
public LruBitmapCache() {
this(getDefaultLruCacheSize());
}
public LruBitmapCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}
@Override
protected int sizeOf(String key, Bitmap value) {
return getByteCount / 1024;
...
在上面的代码中,为什么需要除1024,有什么建议?
另外,构造函数LruBitmapCache(int sizeInKiloBytes),为什么参数声明它的大小以千字节为单位?根据上面的文档,它的大小不是应该以字节为单位吗?
任何帮助将不胜感激,谢谢!我很困惑...
最佳答案
LruCache 用于缓存有限数量的值。
但是这个有限数量的值是多少?
第一个选项:您希望在缓存中存储 x
个元素,无论它们在内存中的大小如何。
在本例中,您只需创建一个以 x
作为大小的 LruCache
,并且不重写 sizeOf
方法。
例如:
// cache 1000 values, independently of the String size
LruCache<Integer, String> idToCustomerName = new LruCache<>(1000);
第二个选项,您希望存储元素,以便所有元素的大小总和不超过给定数量。
在本例中,您创建一个以 y
作为总体大小的 LruCache
,并且您确实覆盖了指定大小的 sizeOf
缓存中的元素。
例如:
// cache an undefined number of ids so that the length of all the strings
// do not exceed 100000 characters
LruCache<Integer, String> idToCustomerName = new LruCache<>(100000) {
@Override
protected int sizeOf(Integer key, String value) {
return value.length();
}
};
为了回答您有关代码的问题,只要 maxSize
变量和 sizeOf
的单位相同,缓存中使用的单位并不重要。
在您的示例中,缓存的内部单位是千字节,因此您会在代码中看到 /1024
和 /8
,它们与 匹配getByteCount/1024;
在 sizeOf
方法中。
关于java - 如果我在使用 LruCache 类时不重写 sizeof 会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25608497/