zoukankan      html  css  js  c++  java
  • java基于Hash表和双向链表简单实现LRU Cache

    package lru;
    
    import java.util.HashMap;
    
    public class LRUCache2<K,V> {
        public final int capacity;
        class DNode{
            K key;
            V value;
            DNode next;
            DNode pre;
            public DNode(K key, V value, LRUCache2<K, V>.DNode pre, LRUCache2<K, V>.DNode next) {
                super();
                this.key = key;
                this.value = value;
                this.pre = pre;
                this.next = next;
            }
            
        }
        
      //附加头结点 DNode head
    =new DNode(null,null,null,null); DNode last=head; HashMap<K,DNode> map=new HashMap<>(); public LRUCache2(int capacity) { this.capacity=capacity; } public V get(K key) { DNode node=map.get(key); if(node!=null) { moveToHead(node); } return node==null?null:node.value; } public void put(K key, V value) { DNode node=map.get(key); if(node==null) { if(map.size()>=capacity) { removeLast(); } node=new DNode(key, value,head,head.next); if(head.next!=null) head.next.pre=node; head.next=node; map.put(node.key, node); if(last==head) last=node; }else { node.value=value; moveToHead(node); } } private void removeLast() { // TODO Auto-generated method stub if(last==null) { throw new IllegalArgumentException("cant remove before put"); } map.remove(last.key); last.pre.next=null; last=last.pre; } private void moveToHead(LRUCache2<K, V>.DNode node) { // TODO Auto-generated method stub if(head.next==node) return; if(last==node) { last=node.pre; } node.pre.next=node.next; if(node.next!=null) node.next.pre=node.pre; node.next=head.next; node.pre=head; head.next.pre=node; head.next=node; } }
  • 相关阅读:
    Spring-web初始化流程简图
    记一次升级Tomcat
    Spring-Task思维导图
    2019的第一个工作日
    RocketMQ专题2:三种常用生产消费方式(顺序、广播、定时)以及顺序消费源码探究
    RocketMQ专题1:入门
    博客搬家到云栖社区
    ActiveMQ专题2: 持久化
    ActiveMQ专题1: 入门实例
    linux下怎么卸载自带的JDK和安装想要的JDK
  • 原文地址:https://www.cnblogs.com/lshao/p/9650673.html
Copyright © 2011-2022 走看看