import java.util.HashMap; public class LruCache<K> { private HashMap<K, Entry> map; private Entry<K> head; private Entry<K> tail; private int cap; private int size; public LruCache(int cap) { if (cap<1) { throw new IllegalArgumentException(); } this.map = new HashMap<>(); this.cap = cap; } public HashMap getMap() { return map; } private static class Entry<K> { private K key; private Entry<K> before; private Entry<K> after; public Entry( K key,Entry<K> before,Entry<K> after){ this.key = key; this.before = before; this.after = after; } public K getKey() { return key; } public void setKey(K key) { this.key = key; } public Entry<K> getBefore() { return before; } public void setBefore(Entry<K> before) { this.before = before; } public Entry<K> getAfter() { return after; } public void setAfter(Entry<K> after) { this.after = after; } @Override public String toString() { return "Entry{" + "key=" + key + ‘}‘; } } public void put(K key) { Entry<K> e; if (tail == null) { head = tail = e = new Entry<>(key, null, null); } else{ Entry<K> last = tail; e = new Entry<>(key, last, null); last.after = e; tail = e; } size++; if (size>cap) { Entry<K> first = head; Entry<K> second = first.after; second.before = null; head = second; map.remove(first.getKey()); } map.put(key, e); } public K get(K key){ Entry<K> e = map.get(key); if (e != null) { Entry<K> prev = e.before; Entry<K> next = e.after; prev.after = next; next.before =prev; tail = e; return e.getKey(); } else { return null; } } public static void main(String[] args) { LruCache<Integer> cache = new LruCache<>(3); System.out.println(cache.get(1)); cache.put(1); cache.put(2); cache.put(3); cache.put(4); cache.put(1); System.out.println(cache.getMap()); } }
null
{1=Entry{key=1}, 3=Entry{key=3}, 4=Entry{key=4}}
package com.ruoyi; import java.util.LinkedHashMap; import java.util.Map; public class LruCache2 extends LinkedHashMap{ private int cap; public LruCache2(int cap){ super(16, 0.75f,true); this.cap = cap; } @Override public boolean removeEldestEntry(Map.Entry eldestEntry){ return size() > cap; } public static void main(String[] args) { LruCache2 cache = new LruCache2(2); cache.put(1,1); cache.put(2,2); cache.put(3,3); cache.put(4,4); cache.put(5,5); cache.put(6,6); System.out.println(cache.get(1)); System.out.println(cache.get(2)); System.out.println(cache.get(3)); System.out.println(cache.get(4)); System.out.println(cache.get(5)); System.out.println(cache.get(6)); } }
null
null
null
null
5
6
原文:https://www.cnblogs.com/tonggc1668/p/11925214.html