import java.util.LinkedHashMap;
import java.util.Map; public class LRUCache<K, V> extends LinkedHashMap<K, V> {
private static final int MAX_CACHE_SIZE = 100; private int limit; public LRUCache() {
this(MAX_CACHE_SIZE);
} public LRUCache(int cacheSize) {
super(cacheSize, 0.75f, true);
this.limit = cacheSize;
} public V save(K key, V val) {
return put(key, val);
} public V getOne(K key) {
return get(key);
} public boolean exists(K key) {
return containsKey(key);
} /**
* 判断节点数是否超限
* @param eldest
* @return 超限返回 true,否则返回 false
*/
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > limit;
} @Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (Map.Entry<K, V> entry : entrySet()) {
sb.append(String.format("%s:%s ", entry.getKey(), entry.getValue()));
}
return sb.toString();
} public static void main(String[] args){
LRUCache<String, Integer> cache = new LRUCache<>(3); for (int i = 0; i < 10; i++) {
cache.save("I" + i, i * i);
}
System.out.println(cache);
System.out.println("插入10个键值对后,缓存内容为:");
System.out.println(cache + "\n"); System.out.println("访问键值为I8的节点后,缓存内容为:");
cache.getOne("I8");
System.out.println(cache + "\n"); System.out.println("插入键值为I1的键值对后,缓存内容:");
cache.save("I1", 1);
System.out.println(cache);
System.out.println("size:"+cache.size());
}
}

  

最新文章

  1. Cloud Engine:大杀器如何炼成
  2. Asp.Net Core--基于声明的授权
  3. Tomcat与Jre绿色环境配置(生产环境)
  4. maven导入本地jar包
  5. HtmlAgilityPack---Html解析框架
  6. 利用 Process Monitor 找出某个 Windows 选项所对应的注册表值
  7. RelativeLayout布局
  8. 浙江理工2015.12校赛-A
  9. Linux运维命令之一
  10. window下部署php_redis扩展
  11. [android]如何让TextView使用超链接
  12. 51nod动态规划-----矩阵取数
  13. HDU1247 Hat’s Words(Trie的动态内存版本)
  14. [Angular 2] Handling Clicks and Intervals Together with Merge
  15. Set up HTTP/2 server with Spring Boot 【基于Spring boot搭建http2.0服务器】
  16. 【渗透课程】第二篇上-http请求协议的简单描述
  17. LeetCode 543. Diameter of Binary Tree (二叉树的直径)
  18. Tomcat 集群中 实现session 共享的三种方法
  19. vue-cli3.0怎么修改端口?
  20. 苹果ANCS协议学习【转】

热门文章

  1. Vue的安装和使用详解(一)
  2. Ubuntu安装可视化电脑配置视图工具neofetch
  3. Openstack组件部署 — Overview和前期环境准备
  4. SQLSERVER 时间日期函数,查询今天日期、昨天、一个星期、半年前的数据
  5. 1.0搭建 Node.js 开发环境
  6. win10 打开 sql sever配置管理器
  7. python基础【第七篇】
  8. Java技术专区-虚拟机系列-堆快照(获取)
  9. Python之循环遍历
  10. 回头看看HTML5