Simple implementation for LRUCache (16.25) #2.
parent
9edde0b72e
commit
50cc9b8f5b
|
@ -1,9 +1,9 @@
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
|
||||||
public class LruCache<K,V> implements Map<K,V> {
|
public class LruCache<K,V> implements Map<K,V> {
|
||||||
private Map<K,V> map;
|
private final Map<K,V> map;
|
||||||
private PriorityQueue<Object> priorityQueue;
|
private final PriorityQueue<K> priorityQueue;
|
||||||
private Map<Object,Integer> counts;
|
private final Map<K,Integer> counts;
|
||||||
private final int maxSize;
|
private final int maxSize;
|
||||||
|
|
||||||
public LruCache(int maxSize) {
|
public LruCache(int maxSize) {
|
||||||
|
@ -34,9 +34,9 @@ public class LruCache<K,V> implements Map<K,V> {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public V get(Object key) {
|
public V get(Object key) {
|
||||||
counts.put(key, counts.getOrDefault(key, 0) + 1);
|
counts.put((K) key, counts.getOrDefault(key, 0) + 1);
|
||||||
priorityQueue.remove(key);
|
priorityQueue.remove(key);
|
||||||
priorityQueue.add(key);
|
priorityQueue.add((K) key);
|
||||||
return map.get(key);
|
return map.get(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1,20 +1,24 @@
|
||||||
|
import java.io.PrintStream;
|
||||||
|
|
||||||
public class Program {
|
public class Program {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
testLruCache(System.out);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void testLruCache(PrintStream ps) {
|
||||||
var lruCache = new LruCache<>(2);
|
var lruCache = new LruCache<>(2);
|
||||||
lruCache.put(1, "one");
|
lruCache.put(1, "one");
|
||||||
lruCache.put(2, "two");
|
lruCache.put(2, "two");
|
||||||
|
ps.println("Element: " + lruCache.get(1));
|
||||||
System.out.println("Element: " + lruCache.get(1));
|
ps.println("Element: " + lruCache.get(1));
|
||||||
System.out.println("Element: " + lruCache.get(1));
|
ps.println("Element: " + lruCache.get(1));
|
||||||
System.out.println("Element: " + lruCache.get(1));
|
|
||||||
|
|
||||||
lruCache.put(3, "three");
|
lruCache.put(3, "three");
|
||||||
System.out.println("Element: " + lruCache.get(2));
|
ps.println("Element: " + lruCache.get(2));
|
||||||
lruCache.put(4, "four");
|
lruCache.put(4, "four");
|
||||||
System.out.println("Element: " + lruCache.get(4));
|
ps.println("Element: " + lruCache.get(4));
|
||||||
System.out.println("Element: " + lruCache.get(3));
|
ps.println("Element: " + lruCache.get(3));
|
||||||
System.out.println("Element: " + lruCache.get(2));
|
ps.println("Element: " + lruCache.get(2));
|
||||||
System.out.println("Element: " + lruCache.get(1));
|
ps.println("Element: " + lruCache.get(1));
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue