-
Notifications
You must be signed in to change notification settings - Fork 6.4k
Expand file tree
/
Copy pathLRUCache.java
More file actions
46 lines (40 loc) · 1.25 KB
/
Copy pathLRUCache.java
File metadata and controls
46 lines (40 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package lrucache;
import java.util.HashMap;
import java.util.Map;
public class LRUCache<K, V> {
private final int capacity;
private final Map<K, Node<K, V>> map;
private final DoublyLinkedList<K, V> dll;
public LRUCache(int capacity) {
this.capacity = capacity;
this.map = new HashMap<>();
this.dll = new DoublyLinkedList<>();
}
public synchronized V get(K key) {
if (!map.containsKey(key)) return null;
Node<K, V> node = map.get(key);
dll.moveToFront(node);
return node.value;
}
public synchronized void put(K key, V value) {
if (map.containsKey(key)) {
Node<K, V> node = map.get(key);
node.value = value;
dll.moveToFront(node);
} else {
if (map.size() == capacity) {
Node<K, V> lru = dll.removeLast();
if (lru != null) map.remove(lru.key);
}
Node<K, V> newNode = new Node<>(key, value);
dll.addFirst(newNode);
map.put(key, newNode);
}
}
public synchronized void remove(K key) {
if (!map.containsKey(key)) return;
Node<K, V> node = map.get(key);
dll.remove(node);
map.remove(key);
}
}