public class LRUCache<K, V> extends LinkedHashMap<K, V> { private static final long serialVersionUID = 3125099067311409227L; private Integer cacheSize; public LRUCache(Integer cacheSize) { super(cacheSize * 3/ 4 + 1, 0.75f, true); this.cacheSize = cacheSize; } @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { if (size() > cacheSize) { return true; } return false; //return super.removeEldestEntry(eldest); } }
public class MyTest { public static void main(String[] args) { Map<String, String> map = new LRUCache<>(4); map.put("1", "1"); map.put("2", "2"); map.put("3", "3"); map.put("4", "4"); map.put("5", "5"); map.put("6", "6"); map.put("1", "1"); //map.get("3"); //map.get("6"); //map.get("1"); for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + "=========" + entry.getValue()); } } }
运行结果:
4=========4 5=========5 6=========6 1=========1