|
5 | 5 | import java.util.Map; |
6 | 6 |
|
7 | 7 | /** |
8 | | - * Created by IntelliJ IDEA. |
9 | | - * <p/> |
10 | 8 | * A simple LRU cache using {@link LinkedHashMap}. A special |
11 | 9 | * LinkedHashMap(capacity, loadFactor, accessOrderBoolean) constructor is |
12 | 10 | * provided to create a linked hash map whose order of iteration is the |
|
15 | 13 | * in an access to the corresponding entry. If the enclosing Map is |
16 | 14 | * access-ordered, it moves the entry to the end of the list; otherwise, |
17 | 15 | * it does nothing. |
| 16 | + * See <a href="http://javarticles.com/2012/06/linkedhashmap.html">Javarticles.com</a>. |
18 | 17 | * |
19 | 18 | * @author rampatra |
20 | | - * @link http://javarticles.com/2012/06/linkedhashmap.html |
21 | 19 | * @since 7/8/15 |
22 | 20 | */ |
23 | | -public class LRUCache<E> { |
| 21 | +public class LRUCache<E, V> { |
24 | 22 |
|
25 | | - LinkedHashMap linkedHashMap; |
| 23 | + LinkedHashMap<E, V> linkedHashMap; |
26 | 24 |
|
27 | 25 | // initialize cache |
28 | 26 | LRUCache(final int size) { |
29 | | - this.linkedHashMap = new LinkedHashMap(size, .75f, true) { |
| 27 | + this.linkedHashMap = new LinkedHashMap<E, V>(size, .75f, true) { |
30 | 28 | @Override |
31 | 29 | protected boolean removeEldestEntry(Map.Entry eldest) { |
32 | 30 | return size() > size; |
33 | 31 | } |
34 | 32 | }; |
35 | 33 | } |
36 | 34 |
|
37 | | - void add(E item) { |
38 | | - linkedHashMap.put(item, null); |
39 | | - printCache(); |
| 35 | + V add(E key, V value) { |
| 36 | + return linkedHashMap.put(key, value); |
40 | 37 | } |
41 | 38 |
|
42 | | - E get(E item) { |
43 | | - E itemFromCache = (E) linkedHashMap.get(item); |
44 | | - if (itemFromCache == null) { |
45 | | - add(item); |
46 | | - return item; |
47 | | - } |
48 | | - printCache(); |
49 | | - return itemFromCache; |
| 39 | + V get(E key) { |
| 40 | + return linkedHashMap.get(key); |
50 | 41 | } |
51 | 42 |
|
52 | | - private void printCache() { |
| 43 | + private void print() { |
53 | 44 | Iterator<E> iterator = linkedHashMap.keySet().iterator(); |
54 | 45 | while (iterator.hasNext()) { |
55 | 46 | System.out.print(iterator.next() + ((iterator.hasNext()) ? "," : "\n")); |
56 | 47 | } |
57 | 48 | } |
58 | 49 |
|
59 | 50 | public static void main(String[] a) { |
60 | | - LRUCache<Integer> cache = new LRUCache<>(3); |
61 | | - cache.add(1); |
62 | | - cache.add(2); |
63 | | - cache.add(3); |
64 | | - cache.get(null); |
65 | | - cache.add(4); |
66 | | - cache.add(5); |
67 | | - cache.get(null); |
| 51 | + LRUCache<Integer, Integer> cache = new LRUCache<>(3); |
| 52 | + cache.add(1, 1); |
| 53 | + cache.add(2, 2); |
| 54 | + cache.add(3, 3); |
| 55 | + cache.print(); |
| 56 | + if (cache.get(4) == null) { |
| 57 | + cache.add(4, 4); |
| 58 | + } |
| 59 | + cache.print(); |
| 60 | + cache.add(5, 5); |
| 61 | + cache.print(); |
68 | 62 | } |
69 | 63 | } |
0 commit comments