Java 继承 LinkedHashMap 实现LRU算法
2018-07-20 来源:open-open
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* 此类通过继承 LinkedHashMap 实现LRU算法(当 accessOrder 设置成 true 时)
*
* @author hanshubo
*
* @param <K>
* @param <V>
*/
public class MyLinkedMap<K, V> extends LinkedHashMap<K, V> {
/**
*
* @param accessOrder
* 设置成 true 时,为最近最少使用(LRU)算法实现, 设置成 false 时,为先进入先过期
*/
public MyLinkedMap(boolean accessOrder) {
super(16, 0.75f, accessOrder);
}
/**
* 队列最大容量,超过此容量时,会将最“旧”数据删除掉
*/
private static final int MAX_ENTRIES = 1000;
/**
* 重写父类方法,实现LRU算法
*/
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > MAX_ENTRIES;
}
public static void main(String[] args) {
MyLinkedMap<Integer, Integer> map = new MyLinkedMap<Integer, Integer>(false);
map.put(1, 0);
map.put(2, 0);
map.put(3, 0);
map.put(4, 0);
map.put(5, 0);
map.put(2, 0);
map.put(1, 0);
for (Entry<Integer, Integer> e : map.entrySet()) {
System.out.println(e.getKey());
}
}
}
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
上一篇: Android获取App版本号和版本名
最新资讯
热门推荐