LRU实现

·
import java.util.HashMap;
import java.util.Map;

/**

  • @author

  • @date 2020/3/11 17:46

  • @desc
    */
    public class DoubleLink {
    LRUNode head;
    LRUNode tail;

    int capacity;
    Map map;

    public DoubleLink(int capacity) {
    super();
    this.capacity = capacity;
    map = new HashMap<>(capacity);
    }

    public void set(String key, String value) {
    LRUNode node = map.get(key);
    if (node == null) {
    //判断是否超出最大长度
    if (map.size() == capacity) {
    remove(tail, true);
    }
    node = new LRUNode(key, value);
    setHead(node);
    map.put(key, node);
    return;
    }

     remove(node, false);
     node.value = value;
     setHead(node);
    

    }

    public LRUNode get(String key) {
    //map中查找
    LRUNode node = map.get(key);
    if (node == null) {
    return null;
    }
    //node 存在,将node从链表中删除,并把node放到队头
    remove(node, false);

     setHead(node);
     return node;
    

    }

    public void setHead(LRUNode node) {
    if (head == null) {
    head = node;
    tail = node;
    return;
    }

     node.next = head;
     node.prev = null;
     head = node;
    

    }

    /**

    • 移除节点

    • @param node 要移除的节点

    • @param flag 是否需要从map中删除
      */
      private void remove(LRUNode node, boolean flag) {
      if (flag) {
      map.remove(node.key);
      }

      if (node.prev == null) {//node->..
      if (node.next == null) {//node
      head = null;
      tail = null;
      } else {//node->nodeNext
      node.next.prev = null;
      head = node.next;
      }
      } else {
      if (node.next == null) {
      //head->...->node
      node.prev.next = null;
      tail = node.prev;
      } else {
      //head->..->node->...
      node.next.prev = node.prev;
      node.prev.next = node.next;
      }
      }

      node.next = null;
      node.prev = null;
      }

    @Override
    public String toString() {
    return "DoubleLink{" +
    "head=" + head.key +
    ", tail=" + tail.key +
    ", capacity=" + capacity +
    '}';
    }

    public static void main(String[] args) {
    DoubleLink cache = new DoubleLink(3);
    cache.set("1", "2");
    System.out.println(cache);

     cache.set("2", "3");
     System.out.println(cache);
     cache.set("3", "3");
     System.out.println(cache);
     cache.set("4", "3");
     System.out.println(cache);
    
    
     cache.get("3");
     System.out.println(cache);
    

    }
    }

·

你可能感兴趣的:(LRU实现)