当前位置:首页 > 开发 > 编程语言 > 算法 > 正文

LinkedHashMap 最远未被使用丢弃缓存算法Least Recently used

发表于: 2015-05-12   作者:chou_qi   来源:转载   浏览:
摘要: 直接贴代码 类:Test 类: LeastRecentlyUsedLinkedHashMap<K,V> import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Map.Entry; public class Test { public s
直接贴代码

类:Test
类: LeastRecentlyUsedLinkedHashMap<K,V>


import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class Test {
public static void main(String[] args) {
/**
* LinkedHashMap 实现了Least Recently used 最远未被使用丢弃缓存算法
* :在固定大小的LinkedHashMap中如果容量大于了 size() 将丢弃最远时间未被使用的key value 是一种缓存算法
*/

LeastRecentlyUsedLinkedHashMap<String, String> lruMap = new
LeastRecentlyUsedLinkedHashMap<String, String>(5);
lruMap.put("1", "a");
lruMap.put("2", "ab");
lruMap.put("3", "abc");
lruMap.put("4", "abcd");
lruMap.put("5", "abcde");
lruMap.put("6", "abcdef");
lruMap.put("7", "abcdefg");

printMapContent(lruMap);

System.out.println("\n");
lruMap.get("3");
printMapContent(lruMap);

System.out.println("\n");
lruMap.put("8", "xxxxxx");
printMapContent(lruMap);

}

/**
* map循环
* @param lruMap
*/
public static void printMapContent(LeastRecentlyUsedLinkedHashMap lruMap){

Set<Map.Entry<String,String>>  entrySet = lruMap.entrySet();

Iterator iter = entrySet.iterator();

Map.Entry<String,String> entry = null;

while(iter.hasNext()){
entry = (Entry<String, String>) iter.next();
System.out.println("key: " + entry.getKey()+"  value: " +entry.getValue());
}
}
}



LRU算法实现类:


public class LeastRecentlyUsedLinkedHashMap<K,V> extends LinkedHashMap<K,V> {

/**
*
*/
private static final long serialVersionUID = 1L;

/*指定map规定缓存容器长度*/
private int capacity;

LeastRecentlyUsedLinkedHashMap(int capacity){
super(capacity,0.75f,true);
this.capacity = capacity;
}


protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
return size()> capacity;
}

}


LinkedHashMap 最远未被使用丢弃缓存算法Least Recently used

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号