diff --git a/resource/markdown/algorithm/LRUCache.md b/resource/markdown/algorithm/LRUCache.md index 91f159c..953911a 100644 --- a/resource/markdown/algorithm/LRUCache.md +++ b/resource/markdown/algorithm/LRUCache.md @@ -7,7 +7,7 @@ public class LRUCache { /** * 默认容量 */ - private int DEFAULT_CAPACITY = 1024; + private static final int DEFAULT_CAPACITY = 1024; /** * 缓存容量 */ @@ -19,19 +19,21 @@ public class LRUCache { /** * 高效访问的散列表 */ - private Map> map; + private Map> map; - private Node head, tail; + private Node head, tail; /** * 自定义双向链表中的节点 */ - private static class Node { + private static class Node { + K key; V value; - Node prev; - Node next; + Node prev; + Node next; - Node(Node prev, V value, Node next) { + Node(Node prev, K key, V value, Node next) { + this.key = key; this.value = value; this.prev = prev; this.next = next; @@ -46,6 +48,10 @@ public class LRUCache { } public LRUCache(int capacity) { + if (capacity <= 0) { + throw new IllegalArgumentException("Capacity must be positive integer"); + } + this.capacity = capacity; this.map = new HashMap<>(capacity, 0.75F); this.head = null; @@ -53,7 +59,7 @@ public class LRUCache { } public V get(K key) { - Node node = this.map.get(key); + Node node = this.map.get(key); if (node != null) { this.moveToHead(node); return node.value; @@ -63,7 +69,7 @@ public class LRUCache { } public V put(K key, V value) { - Node node = this.map.get(key); + Node node = this.map.get(key); if (node != null) { node.value = value; moveToHead(node); @@ -71,11 +77,11 @@ public class LRUCache { } if (size == capacity) { - removeLast(); - map.remove(key); + node = removeLast(); + map.remove(node.key); } - node = addFirst(value); + node = addFirst(key, value); map.put(key, node); return value; @@ -84,9 +90,9 @@ public class LRUCache { /** * 对于新添加的元素,应将新元素添加到链表的头部 */ - private Node addFirst(V e) { - final Node h = head; - final Node newNode = new Node<>(null, e, h); + private Node addFirst(K key, V value) { + final Node h = head; + final Node newNode = new Node<>(null, key, value, h); head = newNode; if (h == null) { tail = newNode; @@ -101,9 +107,9 @@ public class LRUCache { /** * 对于被访问的元素,将该元素移动到头部 */ - private Node moveToHead(Node node) { - final Node prev = node.prev; - final Node next = node.next; + private Node moveToHead(Node node) { + final Node prev = node.prev; + final Node next = node.next; if (prev == null) { // 如果是首节点,无需移动 return node; @@ -127,15 +133,14 @@ public class LRUCache { /** * 缓存满时,应删除(淘汰)最后一个节点 */ - private V removeLast() { - final Node t = tail; + private Node removeLast() { + final Node t = tail; if (t == null) { return null; } - V element = t.value; t.value = null; // help GC - Node prev = t.prev; + Node prev = t.prev; t.prev = null; // help GC tail = prev; // 移动 tail if (prev == null) { // 如果尾节点的前一个节点也为空,说明尾节点也是首节点 @@ -144,7 +149,7 @@ public class LRUCache { prev.next = null; } size--; - return element; + return t; } } ```