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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
| package cn.shuaijunlan.cache.lru;
import java.util.HashMap;
public class LruCacheOnLinkedAndMap<K, V> {
private class Entry<K, V>{ Entry pre; Entry next; K key; V value; public Entry(K key,V value){ this.key = key; this.value = value; } }
private final int size;
private HashMap<K,Entry<K,V>> map;
private Entry last;
private Entry first;
public LruCacheOnLinkedAndMap(int size){ if (size <= 0){ throw new IllegalArgumentException("The size of Cache must more than zero!"); } this.size = size; map = new HashMap(); }
public void put(K key, V value){ Entry entry = map.get(key); if (entry == null){ if (map.size() >= this.size){ removeLast(); } entry = new Entry(key, value); } entry.value = value; moveToFirst(entry); map.put(key, entry); }
public void removeLast(){ if (last != null){ map.remove(last.key); last = last.pre; if (last == null){ first = null; }else { last.next = null; } } } public Entry get(K key){ Entry entry = map.get(key); if (entry == null){ return null; } moveToFirst(entry); return entry; }
public void moveToFirst(Entry entry){ if (entry == first){ return; } if (entry.pre != null){ entry.pre.next = entry.next; } if (entry.next != null){ entry.next.pre = entry.pre; } if (entry == last){ last = last.pre;
} if (first == null || last == null){ first = last = entry; return; } entry.next = first; first.pre = entry; first = entry; entry.pre = null; }
public void print() { Entry temp = first; while (temp != null){ System.out.println("Key:" + temp.key + " Value:" + temp.value); temp = temp.next; } System.out.println(map.size()); }
public static void main(String[] args) { LruCacheOnLinkedAndMap<String, Integer> lruCacheOnLinkedAndMap = new LruCacheOnLinkedAndMap<>(6); lruCacheOnLinkedAndMap.put("s", 1); lruCacheOnLinkedAndMap.put("h", 2); lruCacheOnLinkedAndMap.put("u", 3); lruCacheOnLinkedAndMap.put("a", 8); lruCacheOnLinkedAndMap.put("i", 4); lruCacheOnLinkedAndMap.put("j", 7); lruCacheOnLinkedAndMap.put("u", 1); lruCacheOnLinkedAndMap.put("s", 10); lruCacheOnLinkedAndMap.print(); }
}
|