原文地址这篇文章简短且能很快明白其中的原理
总结如下:
LRUCache最近最少使用算法,使用的是LinkedHashMap的数据结构
LinkedHashMap<Integer, Integer> linkedHashMap = new LinkedHashMap<Integer, Integer>(
0, 0.75f, true)
构造函数的最后一个参数true为访问顺序,false为插入顺序
LinkedHashMap<Integer, Integer> linkedHashMap = new LinkedHashMap<Integer, Integer>(
0, 0.75f, true);
linkedHashMap.put(1, 1);
linkedHashMap.put(2, 2);
linkedHashMap.put(3, 3);
linkedHashMap.put(4, 4);
linkedHashMap.get(2);
System.out.println(linkedHashMap);
输出结果为1,3,4,2,意思就是最新访问的放在最后
如果为false时则输出为1,2,3,4,和插入顺序不变。
LRUCache.java源码构造函数看出LRUCache使用的就是LinkHashMap以访问顺序这种算法实现
/**
* @param maxSize for caches that do not override {@link #sizeOf}, this is
* the maximum number of entries in the cache. For all other caches,
* this is the maximum sum of the sizes of the entries in this cache.
*/
public LruCache(int maxSize) {
if (maxSize <= 0) {
throw new IllegalArgumentException("maxSize <= 0");
}
this.maxSize = maxSize;
this.map = new LinkedHashMap<K, V>(0, 0.75f, true);
}
public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) {
super(initialCapacity, loadFactor);
this.accessOrder = accessOrder; }
代码备份
public void btn(View v) {
int runtimeSize = (int) Runtime.getRuntime().totalMemory();
// 设置LruCache缓存的大小,一般为当前进程可用容量的1/8。
int maxSize = runtimeSize / 8;
// maxSize的意思就是该缓存最大占用多大的内存,如果存的东西超过这个内存块,就采用最近最少使用策略来删除部分缓存数据,直到缓存大小小于maxSize这个值;
LruCache<String, Bitmap> lruCache = new LruCache<String, Bitmap>(
maxSize) {
@Override
protected int sizeOf(String key, Bitmap value) {
// sizeOf返回的是你缓存的item的大小
// 重写sizeOf方法,计算出要缓存的每张图片的大小
// getRowBytes:Since API Level 1,用于计算位图每一行所占用的内存字节数。
// getByteCount:Since API Level 12,用于计算位图所占用的内存字节数。
return value.getRowBytes() * value.getHeight();
// return value.getByteCount();//计算每张图片的大小
// 经实测发现:getByteCount() = getRowBytes() *
// getHeight(),也就是说位图所占用的内存空间数等于位图的每一行所占用的空间数乘以位图的行数。
// 因为getByteCount要求的API版本较高,因此对于使用较低版本的开发者,在计算位图所占空间时上面的方法或许有帮助
}
@Override
public void trimToSize(int maxSize) {
super.trimToSize(maxSize);
}
};
lruCache.get("");
/**************************************/
LinkedHashMap<Integer, Integer> linkedHashMap = new LinkedHashMap<Integer, Integer>(
0, 0.75f, true);
linkedHashMap.put(1, 1);
linkedHashMap.put(2, 2);
linkedHashMap.put(3, 3);
linkedHashMap.put(4, 4);
linkedHashMap.get(2);
System.out.println(linkedHashMap);//输出结果为1,3,4,2
}