LRUCache.java
1package org.udger.parser;
2
3import java.io.Serializable;
4import java.util.HashMap;
5import java.util.Map;
6
10public class LRUCache<K, V> implements Serializable {
11
12 private static final long serialVersionUID = 275929298283639982L;
13
14 private static class Node<K, V> implements Serializable {
15 private static final long serialVersionUID = -2815264316130381309L;
16 private Node<K, V> prev;
17 private Node<K, V> next;
18 private K key;
19 private V value;
20 }
21
22 private Node<K, V> head;
23 private Node<K, V> tail;
24 private int capacity;
25
26 private final Map<K, Node<K, V>> map = new HashMap<>();
27
28 public LRUCache(int capacity) {
29 this.capacity = capacity;
30 }
31
32 public int getCapacity() {
33 return capacity;
34 }
35
36 public void setCapacity(int capacity) {
37 if (this.capacity > capacity) {
38 while (map.size() > capacity) {
39 assert (tail != null);
40 map.remove(tail.key);
41 tail = tail.prev;
42 tail.next = null;
43 }
44 }
45 this.capacity = capacity;
46 }
47
48 public void clear() {
49 this.map.clear();
50 }
51
52 public V get(K uaString) {
53 Node<K, V> node = map.get(uaString);
54 if (node != null) {
55 if (head != node) {
56 if (node.next != null) {
57 node.next.prev = node.prev;
58 } else {
59 tail = node.prev;
60 }
61 node.prev.next = node.next;
62 head.prev = node;
63 node.next = head;
64 node.prev = null;
65 head = node;
66 }
67 return node.value;
68 }
69 return null;
70 }
71
72 public void put(K key, V value) {
73 Node<K, V> node = map.get(key);
74 if (node == null) {
75 node = new Node<>();
76 node.value = value;
77 node.key = key;
78 node.next = head;
79 node.prev = null;
80 if (head != null) {
81 head.prev = node;
82 }
83 if (tail == null) {
84 tail = head;
85 }
86 head = node;
87 map.put(key, node);
88 if (map.size() > capacity) {
89 assert (tail != null);
90 map.remove(tail.key);
91 tail = tail.prev;
92 tail.next = null;
93 }
94 }
95 node.value = value;
96 }
97
98}
99