在上面2篇文章中,讲述了LinkedHashMap实现LRU的方式。那我们不借助它,纯手写呢?实现思想和LinkedHashMap的put(K key, V value)、get(Object key)的原理大致一样,只是盛放的容器该如何选择。在这里,我们选用HashMap,因为其的put(K key, V value)、get(Object key)方法的时间复杂度均为O(1),性能上佳。下面我们贴出代码:
import java.util.*;
public class LRUCache {
private int capacity;
private HashMap<String, ListNode> hashmap;
private ListNode head;
private ListNode tail;
class ListNode{
String key;
int val;
ListNode prev;
ListNode next;
public ListNode(){
}
public ListNode(String key, int val){
this.key = key;
this.val = val;
}
}
public LRUCache(int capacity) {
this.capacity = capacity;
hashmap = new HashMap<>();
head = new ListNode();
tail = new ListNode();
head.next = tail;
tail.prev = head;
}
public void put(String key, int value) {
if(hashmap.containsKey(key)){
ListNode node = hashmap.get(key);
node.val = value;
moveNodeToLast(node);
return;
}
if(hashmap.size() == capacity){
hashmap.remove(head.next.key);
removeNode(head.next);
}
ListNode node = new ListNode(key, value);
hashmap.put(key, node);
addNodeToLast(node);
}
public int get(String key) {
if(hashmap.containsKey(key)){
ListNode node = hashmap.get(key);
moveNodeToLast(node);
return node.val;
}
else{
return -1;
}
}
/**
* 把node元素从双向链表中移除
*/
private void removeNode(ListNode node){
node.prev.next = node.next;
node.next.prev = node.prev;
}
/**
* 把node元素追加到双向链表的尾部
*/
private void addNodeToLast(ListNode node){
node.prev = tail.prev;
node.prev.next = node;
node.next = tail;
tail.prev= node;
}
/**
* 把node元素移动到双向链表的尾部
*/
private void moveNodeToLast(ListNode node){
removeNode(node);
addNodeToLast(node);
}
public Set<ListNode> enteySet() {
return new Set1<>();
}
class Set1<E> extends AbstractSet<E> {
@Override
public Iterator<E> iterator() {
return new Iterator1();
}
@Override
public int size() {
return hashmap.size();
}
}
class Iterator1 implements Iterator {
private ListNode node;
public Iterator1() {
super();
node = head;
}
@Override
public boolean hasNext() {
return node.next != tail;
}
@Override
public ListNode next() {
node = node.next;
return node;
}
}
}
具体使用:
public static void main(String[] args) {
LRUCache lru = new LRUCache(5);
String[] arr = "abcde".split("");
for(int i = 0; i < arr.length; i++) {
lru.put(arr[i], i);
}
lru.get("a");
lru.put("f", 5);
for (LRUCache.ListNode node : lru.enteySet()) {
System.out.println("key:" + node.key + ",value:" + node.val);
}
}
运行截图: