forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLRUCache.java
63 lines (55 loc) · 1.46 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package me.ramswaroop.linkedlists;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Created by IntelliJ IDEA.
* <p/>
* A simple LRU cache using {@link java.util.LinkedHashMap}.
*
* @author: ramswaroop
* @date: 7/8/15
* @time: 5:40 PM
* @see: http://javarticles.com/2012/06/linkedhashmap.html
*/
public class LRUCache<E> {
LinkedHashMap linkedHashMap;
// initialize cache
LRUCache(final int size) {
this.linkedHashMap = new LinkedHashMap(size, .75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > size;
}
};
}
void add(E item) {
linkedHashMap.put(item, null);
printCache();
}
E get(E item) {
E itemFromCache = (E) linkedHashMap.get(item);
if (itemFromCache == null) {
add(item);
return item;
}
printCache();
return itemFromCache;
}
void printCache() {
Iterator<E> iterator = linkedHashMap.keySet().iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + ((iterator.hasNext()) ? "," : "\n"));
}
}
public static void main(String a[]) {
LRUCache<Integer> cache = new LRUCache<>(3);
cache.add(1);
cache.add(2);
cache.add(3);
cache.get(null);
cache.add(4);
cache.add(5);
cache.get(null);
}
}