LRU 算法

来源:互联网 发布:plc编码器编程 编辑:程序博客网 时间:2024/05/22 13:54

最近在工作中遇到LRU算法,本人写了个实现,供大家参考,吐槽。


public class CacheLRU<K,V>{


    private int maxSize=10;
    private HashMap<K,Entry> map=new HashMap<K,Entry>();


    public CacheLRU(int size){
       this.maxSize=size;
    }


    private Entry head=null;
    private Entry tail=null;


    public void put(K key,V value){
        Entry entry=new Entry();
        entry.key=key;
        entry.value=value;
        putEntryToHead(entry);
    }




    public V get(K key){
        Entry<K,V> result=null;
        result=map.get(key);
        if(result==null){
            return null;
        }else{
            if(head==result){
                return result.value;
            }else{
               if(tail==result){
                   tail=tail.pre;
                   tail.next=null;
               } else{
                   result.next.pre=result.pre;
                   result.pre.next=result.next;
               }
            }
            map.remove(result.key);
            putEntryToHead(result);
            return result.value;
        }
    }


    private void putEntryToHead(Entry<K,V> entry){
        map.put(entry.key,entry);
        if(head==null){
            head=entry;
            tail=entry;
        }else{
            entry.pre=null;
            entry.next=head;
            head.pre=entry;
            head=entry;
        }
        if(map.size()>maxSize){
            map.remove(tail.key);
            tail=tail.pre;
            tail.next.pre=null;
            tail.next=null;


        }
    }


    public void getAllElements(){


        if(head==null){
            System.out.print("null");
        }else{
           Entry curr=head;
            StringBuffer sb=new StringBuffer();
           while (curr!=null){
               sb.append(curr.key);
               curr=curr.next;
           }
            System.out.println(sb.toString());
        }
    }




    class Entry<K,V>{


        Entry next;
        Entry pre;
        V value;
        K key;
    }


    public static void main(String ag[]){
        CacheLRU<String,String> lru=new CacheLRU<String,String>(3);
        //lru.getAllElements();
        lru.put("3","33");
        lru.put("4","44");
        lru.put("5","55");
       System.out.println(lru.get("3"));
        lru.put("6","66");
        System.out.println(lru.get("5"));
        System.out.println(lru.map.size());
        lru.put("7","777");
        lru.getAllElements();
    }
}
0 0
原创粉丝点击