Skip to content

Commit d76dbfe

Browse files
HARD/src/hard/LRUCache_use_LinkedHashMap.java
1 parent a8edbc1 commit d76dbfe

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package hard;
2+
3+
import java.util.LinkedHashMap;
4+
import java.util.Map;
5+
6+
/**The shortest implementation is to use LinkedHashMap:
7+
* specify a size of the linkedHashMap;
8+
* override the removeEldestEntry method when its size exceeds max size: https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html#removeEldestEntry-java.util.Map.Entry-
9+
* in the constructor, set the last boolean variable to be true: it means the ordering mode, if we set it to true, it means
10+
* in access order, false, means it's in insertion order: https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html#LinkedHashMap-int-float-boolean-*/
11+
public class LRUCache_use_LinkedHashMap {
12+
13+
private Map<Integer, Integer> cache;
14+
private final int max;
15+
16+
public LRUCache_use_LinkedHashMap(int capacity) {
17+
max = capacity;
18+
cache = new LinkedHashMap<Integer, Integer>(capacity, 1.0f, true){
19+
public boolean removeEldestEntry(Map.Entry eldest){
20+
return cache.size() > max;
21+
}
22+
};
23+
}
24+
25+
public int get(int key) {
26+
return cache.getOrDefault(key, -1);
27+
}
28+
29+
public void set(int key, int value) {
30+
cache.put(key, value);
31+
}
32+
}

0 commit comments

Comments
 (0)