LRU缓存(java实现)

import java.util.HashMap;
import java.util.Iterator;

public class LRU implements Iterable  {
    private Node head;
    private Node tail;
    private HashMap map;
    private int maxSize;
    private class Node{
         Node pre;
         Node next;
         K k;
         V v;
         Node(K k,V v){
            this.k=k;
            this.v=v;
        }
    }
    private void unlink(Node node){
        Node preNode=node.pre;
        Node nextNode=node.next;
        preNode.next=nextNode;
        nextNode.pre=preNode;
        node.next=null;
        node.pre=null;
    }
    public V get(K k){
        if(!map.containsKey(k)){
            return null;
        }
        Node node = map.get(k);
        unlink(node);
        appendHead(node);
        return (V)node.v;
    }
    public void set(K k,V v){
        if(map.containsKey(k)){
            unlink(map.get(k));
        }
        Node node = new Node<>(k, v);
        map.put(k,node);
        appendHead(node);
        if(map.size()>maxSize){
            removeOldNode();
        }
    }
    private void removeOldNode() {
        Node node=tail.pre;
        unlink(node);
        map.remove(node.k);
    }

    private void appendHead(Node node){
        Node oldNode=head.next;
        oldNode.pre=node;
        node.next=oldNode;
        head.next=node;
        node.pre=head;
    }
    public LRU(int maxSize){
        this.maxSize=maxSize;
        map=new HashMap<>(maxSize*4/3);
        head=new Node(null,null);
        tail=new Node(null,null);
        head.next=tail;
        tail.pre=head;
    }
    public LRU(){
        this.maxSize=20;
        map=new HashMap<>(maxSize*4/3);
        head=new Node(null,null);
        tail=new Node(null,null);
        head.next=tail;
        tail.pre=head;
    }
    @Override
    public Iterator iterator() {
        return new Iterator() {
            Node node=head.next;
            @Override
            public boolean hasNext() {
                return node!=tail;
            }
            @Override
            public K next() {
                K k = (K)node.k;
                node=node.next;
                return k;
            }
        };
    }
}
//继承LinkedHashMap实现更为简单
class LRULinkedHashMap extends LinkedHashMap{
    private static final int MAX_ENTRIES=3;
    LRULinkedHashMap(){
        super(MAX_ENTRIES,0.75f,true);
    }
    @Override
    protected boolean removeEldestEntry(Map.Entry eldest){
        return size()>MAX_ENTRIES;
    }
}

 

你可能感兴趣的:(java)