标签:
本文就 《基于LinkedHashMap实现LRU缓存调度算法原理及应用 》一文作为材料,记录一些常见问题,备忘。
LinkedHashMap继承了HashMap底层是通过Hash表+单向链表实现Hash算法,内部自己维护了一套元素访问顺序的列表。
import java.util.LinkedHashMap;
public class URLLinkedListHashMap<K, V> extends LinkedHashMap<K, V> {
/**
*
*/
private static final long serialVersionUID = 1L;
/** 最大数据存储容量 */
private static final int LRU_MAX_CAPACITY = 1024;
/** 存储数据容量 */
private int capacity;
/**
* 默认构造方法
*/
public URLLinkedListHashMap() {
super();
}
/**
* 带参数构造方法
* @param initialCapacity 容量
* @param loadFactor 装载因子
* @param isLRU 是否使用lru算法,true:使用(按方案顺序排序);false:不使用(按存储顺序排序)
*/
public URLLinkedListHashMap(int initialCapacity, float loadFactor, boolean isLRU) {
super(initialCapacity, loadFactor, isLRU);
capacity = LRU_MAX_CAPACITY;
}
public URLLinkedListHashMap(int initialCapacity, float loadFactor, boolean isLRU,int lruCapacity) {
super(initialCapacity, loadFactor, isLRU);
this.capacity = lruCapacity;
}
@Override
protected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest) {
// TODO Auto-generated method stub
return super.removeEldestEntry(eldest);
}
}测试代码:
import java.util.LinkedHashMap;
import java.util.Map.Entry;
public class LRUTest {
public static void main(String[] args) {
LinkedHashMap<String, String> map = new URLLinkedListHashMap(16, 0.75f, false);
map.put("a", "a"); //a a
map.put("b", "b"); //a a b
map.put("c", "c"); //a a b c
map.put("a", "a"); // b c a
map.put("d", "d"); //b b c a d
map.put("a", "a"); // b c d a
map.put("b", "b"); // c d a b
map.put("f", "f"); //c c d a b f
map.put("g", "g"); //c c d a b f g
map.get("d"); //c a b f g d
for (Entry<String, String> entry : map.entrySet()) {
System.out.print(entry.getValue() + ", ");
}
System.out.println();
map.get("a"); //c b f g d a
for (Entry<String, String> entry : map.entrySet()) {
System.out.print(entry.getValue() + ", ");
}
System.out.println();
map.get("c"); //b f g d a c
for (Entry<String, String> entry : map.entrySet()) {
System.out.print(entry.getValue() + ", ");
}
System.out.println();
map.get("b"); //f g d a c b
for (Entry<String, String> entry : map.entrySet()) {
System.out.print(entry.getValue() + ", ");
}
System.out.println();
map.put("h", "h"); //f f g d a c b h
for (Entry<String, String> entry : map.entrySet()) {
System.out.print(entry.getValue() + ", ");
}
System.out.println();
}
}
答案:
部分转自: http://woming66.iteye.com/blog/1284326
标签:
原文地址:http://blog.csdn.net/langjian2012/article/details/45184303