-
Notifications
You must be signed in to change notification settings - Fork 26
/
LruCache.java
46 lines (40 loc) · 1.2 KB
/
LruCache.java
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 linkedlist.problems.lru;
import java.util.HashMap;
public class LruCache {
private final int CACHE_MAX_SIZE;
private int CACHE_SIZE;
private HashMap<Integer, Integer> cacheMap;
private DoublyList doublyList;
LruCache(int capacity) {
this.CACHE_SIZE = 0;
this.CACHE_MAX_SIZE = capacity;
this.cacheMap = new HashMap<>();
this.doublyList = new DoublyList();
}
public int get(int key) {
if (this.cacheMap.containsKey(key)) {
this.doublyList.refreshNode(key);
return this.cacheMap.get(key);
} else {
return -1;
}
}
public void put(int key, int value) {
if (this.cacheMap.containsKey(key)) {
// Key already exists.
this.cacheMap.put(key, value);
this.doublyList.refreshNode(key);
return;
}
this.cacheMap.put(key, value);
this.CACHE_SIZE++;
this.doublyList.addNode(key);
checkAndEvict();
}
public void checkAndEvict() {
if (this.CACHE_SIZE > this.CACHE_MAX_SIZE) {
int evictedKey = this.doublyList.evict();
this.cacheMap.remove(evictedKey);
}
}
}