-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCache.java
More file actions
45 lines (38 loc) · 1.01 KB
/
Copy pathLRUCache.java
File metadata and controls
45 lines (38 loc) · 1.01 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
package com.al.lru_cache;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
class LRUCache {
class LRUCacheHelper<K, V> extends LinkedHashMap<K, V> {
private int max;
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > max;
}
LRUCacheHelper(int max) {
super(max, 0.75f, true);
this.max = max;
}
}
private LRUCacheHelper lruh;
LRUCache(int capacity) {
if (capacity <= 0)
throw new IllegalArgumentException("capacity error");
lruh = new LRUCacheHelper(capacity);
}
int get(int key) {
if (lruh == null)
return -1;
return (int) lruh.getOrDefault(key, -1);
}
void put(int key, int value) {
if (lruh != null){
lruh.put(key,value);
}
}
Set keys() throws Exception {
if (lruh == null){
throw new Exception("lrucache need init");
}
return lruh.keySet();
}
}