手写一个LRU工具类
LRU概述
结构设计
1 static class Entry<K,V> {
2 final int hash; // 哈希值
3 final K key; // 键
4 V value; // 值
5 Entry<K,V> before; // 先继节点
6 Entry<K,V> after; // 后继节点
7 Entry(int hash, K key, V value, Entry before, Entry after) {
8 this.hash = hash;
9 this.key = key;
10 this.value = value;
11 this.before = before;
12 this.after = after;
13 }
14 }
1 int maxSize; // 最大容量
2 Entry<K,V> head; // 头节点
3 Entry<K,V> tail; // 尾节点
4 HashMap<K,V> hashMap; // 哈希表
1 // 根据key从链表中找对应节点
2 Entry<K, V> find(Object key) {
3 // 遍历链表找到该元素
4 Entry<K,V> entry = head;
5 while (entry != null) {
6 if (entry.key.equals(key))
7 break;
8 entry = entry.after;
9 }
10 return entry;
11 }
12 // 将key对应的元素移至队首
13 Entry<K,V> moveToFront(Object key) {
14 // 遍历链表找到该元素
15 Entry<K,V> entry = find(key);
16 // 如果找到了并且不是队首,则将该节点移动到队列的首部
17 if (entry != null && entry != head) {
18 // 如果该节点是队尾
19 if (entry == tail)
20 tail = entry.before;
21 // 先将该节点从链表中移出
22 Entry<K,V> p = entry.before;
23 Entry<K,V> q = entry.after;
24 p.after = q;
25 if (q != null)
26 q.before = p;
27 // 然后将该节点作为新的head
28 entry.before = null;
29 entry.after = head;
30 head = entry;
31 }
32 return entry;
33 }
34 // 将key对应的元素从双端链表中删除
35 void removeFromLinkedList(Object key) {
36 // 遍历链表找到该元素
37 Entry<K,V> entry = find(key);
38 // 如果没找到则直接返回
39 if (entry == null) return;
40 // 如果是队首元素
41 if (entry == head) {
42 // 只有一个节点
43 if (tail == head)
44 tail = entry.after;
45 head = entry.after;
46 head.before = null;
47 } else if (entry == tail) {
48 // 如果是队尾元素
49 tail = tail.before;
50 tail.after = null;
51 }
52 }
put()方法
1 // 存入元素/修改元素
2 public void put(K key, V value) {
3 V res = hashMap.put(key,value);
4 // 如果res为null,表示没找到,则存入并放置到队首
5 if (res == null) {
6 Entry<K,V> entry = new Entry<>(key.hashCode(), key, value, null, head);
7 // 如果之前没有头节点
8 if (head == null) {
9 head = entry;
10 tail = entry;
11 } else {
12 // 如果之前有头节点,将头节点before指向entry
13 entry.after = head;
14 head.before = entry;
15 head = entry;
16 }
17 // 判断此时节点数量是否超过最大容量,如果超过,则将队尾元素删除
18 if (hashMap.size() > maxSize) {
19 tail = tail.before;
20 tail.after = null;
21 }
22 } else {
23 // 如果res不为null,表示包含该元素,则将节点放置到队首
24 Entry<K,V> entry = moveToFront(key);
25 // 同时修改节点的V值
26 entry.value = value;
27 }
28 }
remove()方法
1 // 删除元素
2 public void remove(Object key) {
3 V res = hashMap.remove(key);
4 // 如果删除成功,则将链表中节点一并删除
5 if (res != null)
6 removeFromLinkedList(key);
7 }
get()方法
1 // 查询元素
2 public V get(Object key) {
3 V res = hashMap.get(key);
4 // 如果在已有数据中找到,则将该元素放置到队首
5 if (res != null)
6 moveToFront(key);
7 return res;
8 }
完整代码
1 package com.simple.test;
2
3 import java.util.ArrayList;
4 import java.util.HashMap;
5 import java.util.List;
6
7 public class SimpleLRUCache <K,V>{
8 int maxSize; // 最大容量
9 Entry<K,V> head; // 头节点
10 Entry<K,V> tail; // 尾节点
11 HashMap<K,V> hashMap; // 哈希表
12 // 构造函数
13 public SimpleLRUCache(int size) {
14 if (size <= 0)
15 throw new RuntimeException("容器大小不能<=0");
16 this.maxSize = size;
17 this.hashMap = new HashMap<>();
18 }
19 static class Entry<K,V> {
20 final int hash; // 哈希值
21 final K key; // 键
22 V value; // 值
23 Entry<K,V> before; // 先继节点
24 Entry<K,V> after; // 后继节点
25 Entry(int hash, K key, V value, Entry before, Entry after) {
26 this.hash = hash;
27 this.key = key;
28 this.value = value;
29 this.before = before;
30 this.after = after;
31 }
32 }
33 // 查询元素
34 public V get(Object key) {
35 V res = hashMap.get(key);
36 // 如果在已有数据中找到,则将该元素放置到队首
37 if (res != null)
38 moveToFront(key);
39 return res;
40 }
41 // 存入元素/修改元素
42 public void put(K key, V value) {
43 V res = hashMap.put(key,value);
44 // 如果res为null,表示没找到,则存入并放置到队首
45 if (res == null) {
46 Entry<K,V> entry = new Entry<>(key.hashCode(), key, value, null, head);
47 // 如果之前没有头节点
48 if (head == null) {
49 head = entry;
50 tail = entry;
51 } else {
52 // 如果之前有头节点,将头节点before指向entry
53 entry.after = head;
54 head.before = entry;
55 head = entry;
56 }
57 // 判断此时节点数量是否超过最大容量,如果超过,则将队尾元素删除
58 if (hashMap.size() > maxSize) {
59 tail = tail.before;
60 tail.after = null;
61 }
62 } else {
63 // 如果res不为null,表示包含该元素,则将节点放置到队首
64 Entry<K,V> entry = moveToFront(key);
65 // 同时修改节点的V值
66 entry.value = value;
67 }
68 }
69 // 删除元素
70 public void remove(Object key) {
71 V res = hashMap.remove(key);
72 // 如果删除成功,则将链表中节点一并删除
73 if (res != null)
74 removeFromLinkedList(key);
75 }
76 // 将key对应的元素移至队首
77 Entry<K,V> moveToFront(Object key) {
78 // 遍历链表找到该元素
79 Entry<K,V> entry = find(key);
80 // 如果找到了并且不是队首,则将该节点移动到队列的首部
81 if (entry != null && entry != head) {
82 // 如果该节点是队尾
83 if (entry == tail)
84 tail = entry.before;
85 // 先将该节点从链表中移出
86 Entry<K,V> p = entry.before;
87 Entry<K,V> q = entry.after;
88 p.after = q;
89 if (q != null)
90 q.before = p;
91 // 然后将该节点作为新的head
92 entry.before = null;
93 entry.after = head;
94 head = entry;
95 }
96 return entry;
97 }
98 // 将key对应的元素从双端链表中删除
99 void removeFromLinkedList(Object key) {
100 // 遍历链表找到该元素
101 Entry<K,V> entry = find(key);
102 // 如果没找到则直接返回
103 if (entry == null) return;
104 // 如果是队首元素
105 if (entry == head) {
106 // 只有一个节点
107 if (tail == head)
108 tail = entry.after;
109 head = entry.after;
110 head.before = null;
111 } else if (entry == tail) {
112 // 如果是队尾元素
113 tail = tail.before;
114 tail.after = null;
115 }
116 }
117 // 根据key从链表中找对应节点
118 Entry<K, V> find(Object key) {
119 // 遍历链表找到该元素
120 Entry<K,V> entry = head;
121 while (entry != null) {
122 if (entry.key.equals(key))
123 break;
124 entry = entry.after;
125 }
126 return entry;
127 }
128 // 顺序返回元素
129 public List<Entry<K,V>> getList() {
130 List<Entry<K,V>> list = new ArrayList<>();
131 Entry<K,V> p = head;
132 while (p != null) {
133 list.add(p);
134 p = p.after;
135 }
136 return list;
137 }
138 // 顺序输出元素
139 public void print() {
140 Entry<K,V> p = head;
141 while (p != null) {
142 System.out.print(p.key.toString()+":"+p.value.toString()+"\t");
143 p = p.after;
144 }
145 System.out.println();
146 }
147 public static void main(String[] args) {
148 SimpleLRUCache<String, String> test = new SimpleLRUCache(4);
149 test.put("a","1");
150 test.put("b","2");
151 test.put("c","3");
152 test.put("d","4");
153 // 此时顺序为d c b a
154 test.print();
155 // 获取a,此时顺序为 a d c b
156 test.get("a");
157 test.print();
158 // 修改c,此时顺序为 c a d b
159 test.put("c","31");
160 test.print();
161 // 增加e,淘汰末尾元素b,此时顺序为e c a d
162 test.put("e","5");
163 test.print();
164 }
165 }
手写一个LRU工具类的更多相关文章
- 【redis前传】自己手写一个LRU策略 | redis淘汰策略
title: 自己手写一个LRU策略 date: 2021-06-18 12:00:30 tags: - [redis] - [lru] categories: - [redis] permalink ...
- 搞定redis面试--Redis的过期策略?手写一个LRU?
1 面试题 Redis的过期策略都有哪些?内存淘汰机制都有哪些?手写一下LRU代码实现? 2 考点分析 1)我往redis里写的数据怎么没了? 我们生产环境的redis怎么经常会丢掉一些数据?写进去了 ...
- 面试题目:手写一个LRU算法实现
一.常见的内存淘汰算法 FIFO 先进先出 在这种淘汰算法中,先进⼊缓存的会先被淘汰 命中率很低 LRU Least recently used,最近最少使⽤get 根据数据的历史访问记录来进⾏淘汰 ...
- 如何手写一个js工具库?同时发布到npm上
自从工作以来,写项目的时候经常需要手写一些方法和引入一些js库 JS基础又十分重要,于是就萌生出自己创建一个JS工具库并发布到npm上的想法 于是就创建了一个名为learnjts的项目,在空余时间也写 ...
- java中定义一个CloneUtil 工具类
其实所有的java对象都可以具备克隆能力,只是因为在基础类Object中被设定成了一个保留方法(protected),要想真正拥有克隆的能力, 就需要实现Cloneable接口,重写clone方法.通 ...
- 4.redis 的过期策略都有哪些?内存淘汰机制都有哪些?手写一下 LRU 代码实现?
作者:中华石杉 面试题 redis 的过期策略都有哪些?内存淘汰机制都有哪些?手写一下 LRU 代码实现? 面试官心理分析 如果你连这个问题都不知道,上来就懵了,回答不出来,那线上你写代码的时候,想当 ...
- 手写一个HTTP框架:两个类实现基本的IoC功能
jsoncat: 仿 Spring Boot 但不同于 Spring Boot 的一个轻量级的 HTTP 框架 国庆节的时候,我就已经把 jsoncat 的 IoC 功能给写了,具体可以看这篇文章&l ...
- 手把手教你手写一个最简单的 Spring Boot Starter
欢迎关注微信公众号:「Java之言」技术文章持续更新,请持续关注...... 第一时间学习最新技术文章 领取最新技术学习资料视频 最新互联网资讯和面试经验 何为 Starter ? 想必大家都使用过 ...
- 浅析MyBatis(二):手写一个自己的MyBatis简单框架
在上一篇文章中,我们由一个快速案例剖析了 MyBatis 的整体架构与整体运行流程,在本篇文章中笔者会根据 MyBatis 的运行流程手写一个自定义 MyBatis 简单框架,在实践中加深对 MyBa ...
随机推荐
- 锁与同步器的基础--AQS
什么是AQS AQS全名AbstractQueueSynchronizer,可以翻译为抽象队列同步器 Abstract--说明该类需要被继承,提供实现的框架和一些必要的功能 事实上,AQS也的确提供了 ...
- IDEA的注册方式
http://idea.lanyus.com/ 使用前请将"0.0.0.0 account.jetbrains.com"添加到hosts文件中 hosts文件在C:\Windows ...
- Flutter教程- Dart语言规范-知识点整理
Flutter教程- Dart语言知识点整理 Dart语言简介 Dart语言介绍 ① 注释的方式 ② 变量的声明 ③ 字符串的声明和使用 ④ 集合变量的声明 ⑤ 数字的处理 ⑥ 循环的格式 ⑦ 抛异常 ...
- Heron and His Triangle HDU - 6222
题目链接:https://vjudge.net/problem/HDU-6222 思路:打表找规律. 然后因为数据范围较大可以考虑用字符串模拟,或者__int128要注意用一个快读快输模板. 1 #i ...
- windows回收站无法设置
win+r运行 regedit HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer 修改NoRe ...
- 【JVM进阶之路】七:垃圾收集器盘点
在前面,我们已经了解了JVM的分代收集,知道JVM垃圾收集在新生代主要采用标记-复制算法,在老年代主要采用标记-清除和标记-整理算法.接下来,我们看一看JDK默认虚拟机HotSpot的一些垃圾收集器的 ...
- [DFS]特殊的质数肋骨
特殊的质数肋骨 时间限制:1000MS----内存限制:256000KB 题目描述 农民约翰母牛总是产生最好的肋骨. 你能通过农民约翰和美国农业部标记在每根肋骨上的数字认出它们. 农民约翰确定他卖给买 ...
- 2-fabric网络搭建流程
目录 一.示例网络 下面开始一步步的搭建和叙述上述过程 二.创建网络 三.添加网络管理员 四.定义联盟 五.为联盟创建通道 六.节点和账本 七.应用程序和智能合约链码 八.完成网络 简化视觉词汇表 九 ...
- Salesforce学习之路(九)Org的命名空间
1. 命名空间的适用场景 每个组件都是命名空间的一部分,如果Org中设置了命名空间前缀,那么需使用该命名空间访问组件.否则,使用默认命名空间访问组件,系统默认的命名空间为"c". ...
- 大话数据结构.epub
电子书资源:大话数据结构 书籍简介 本书为超级畅销书<大话设计模式>作者程杰潜心三年推出的扛鼎之作!通篇以一种趣味方式来叙述,大量引用了各种各样的生活知识来类比,并充分运用图形语言来体 ...