基于双向链表+hash表
节点对象
public class Node<K,V> {
public K key;
public V value;
public Node<K,V> prev;
public Node<K,V> next;
public Node(K key, V value) {
this.key = key;
this.value = value;
}
public Node() {
}
}
public class LruCache<V> {
/**
容量
*/
private int capacity=1024;
/**
* Node记录表
*/
private Map<String,Node<String,V>> table=new ConcurrentHashMap<>();
/**
* 双向链表头部
*/
private Node<String,V> head;
/**
* 双向链表尾部
*/
private Node<String,V> tail;
public LruCache(int capacity) {
this();
this.capacity = capacity;
}
public LruCache() {
head=new Node<>();
tail=new Node<>();
head.next=tail;
head.prev=null;
tail.prev=head;
tail.next=null;
}
public V get(String key){
Node<String, V> node = table.get(key);
if(node==null){
return null;
}
node.prev.next=node.next;
node.next.prev=node.prev;
//移动节点列表到表头
node.next=head.next;
head.next.prev=node;
node.prev=head;
head.next=node;
return node.value;
}
public void put(String key,V value){
Node<String, V> node = table.get(key);
if(node==null){
if(table.size()==capacity){
table.remove(tail.prev.key);
tail.prev.prev.next=tail;
tail.prev=tail.prev.prev;
}
node=new Node<>();
node.key=key;
node.value=value;
table.put(key,node);
}else{
node.value=value;
table.put(key,node);
}
//移动节点列表到表头
node.next=head.next;
head.next.prev=node;
node.prev=head;
head.next=node;
}
}
测试
LruCache<Node> cache = new LruCache<>(4);
Node<String, Integer> node1 = new Node<>("key1", 1);
Node<String, Integer> node2 = new Node<>("key2", 2);
Node<String, Integer> node3 = new Node<>("key3", 3);
Node<String, Integer> node4 = new Node<>("key4", 4);
Node<String, Integer> node5 = new Node<>("key5", 5);
cache.put("key1", node1);
cache.put("key2", node2);
cache.put("key3", node3);
cache.put("key4", node4);
cache.get("key2");
cache.put("key5", node5);
cache.get("key2");