LRU缓存算法Java实现

最近在学习缓存算法,就自己用java实现了一个LRU缓存算法,其实LRU可以直接用LinkedHashMap直接实现,本文采用HashMap来进行构造代码如下:

 *public class LRUCache<K,V>{
        private class CacheElemet<K,V>{

            private CacheElemet before;
            private CacheElemet next;
            private K key;
            private V value;

            public CacheElemet(K key,V value) {
                this.key=key;
                this.value=value;
            }
        }
        private int capacity=16;
        private HashMap<K,CacheElemet> hs;
        private CacheElemet first=null;
        private CacheElemet last=null;


        public LRUCache(){
            hs=new HashMap<K,CacheElemet>(capacity);
        }

        public LRUCache(int mCapacity) {
            this.capacity=capacity;
            hs=new HashMap<K,CacheElemet>(capacity);
        }

        public V get(K key) {
            if(!hs.containsKey(key)) {
                return null;
            }
            CacheElemet current=hs.get(key);

            current.before.next=current.next;
            current.next.before=current.before;

            addToLast(current);
            return (V)current.value;
        }

        public void put(K key,V value) {

            if(hs.size()==0) {
                first=new CacheElemet(-1,-1);
                last=new CacheElemet(-1,-1);
                first.next=last;
                first.before=last;
                last.next=first;
                last.before=first;
                hs.put(null,first);
                hs.put(null,last);;
            }

            if(hs.containsKey(key)) {
                hs.get(key).value=value;
                return;
            }

            if(hs.size()==capacity) {
                hs.remove(first.next);
                first.next=first.next.next;
                first.next.before=first;
            }
            CacheElemet elemet=new CacheElemet<K,V>(key, value);
            hs.put(key, elemet);
            addToLast(elemet);
        }

        public void addToLast(CacheElemet element) {
            element.before=last.before;
            last.before=element;
            last.before.next=element;
            element.next=last;
        }
}*
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值