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 64 65 66 67 68 69 70 71 72 73
| import java.util.HashMap; import java.util.LinkedList;
public class Main {
static class LRUCache<K, V> { private final int cacheSize; private LinkedList<K> cacheList = new LinkedList<>(); private HashMap<K, V> map = new HashMap<>();
public LRUCache(int cacheSize) { this.cacheSize = cacheSize; }
public synchronized void put(K key, V val) { if (!map.containsKey(key)) { if (map.size() >= cacheSize) { map.remove(cacheList.removeLast()); } cacheList.addFirst(key); map.put(key, val); } else { moveToFirst(key); map.put(key, val); } }
public V get(K key) { if (!map.containsKey(key)) { return null; } moveToFirst(key); return map.get(key); }
private synchronized void moveToFirst(K key) { cacheList.remove(key); cacheList.addFirst(key); }
@Override public String toString() { return cacheList.toString(); } }
public static void main(String[] args) { LRUCache<String, String> lruCache = new LRUCache<String, String>(4); lruCache.put("C", null); lruCache.put("A", null); lruCache.put("D", null); lruCache.put("B", null); lruCache.put("E", null); lruCache.put("B", null); lruCache.put("A", null); lruCache.put("B", null); lruCache.put("C", null); lruCache.put("D", null); System.out.println(lruCache); } }
|