您好,欢迎来到12图资源库!分享精神,快乐你我!我们只是素材的搬运工!!
  • 首 页
  • 当前位置:首页 > 开发 > WEB开发 >
    手写最复杂的LRU算法(2)
    时间:2020-09-18 12:07 来源:网络整理 作者:网络 浏览:收藏 挑错 推荐 打印

               b.after = a;        if (a != null

               a.before = b;        else 

               last = b; 

           if (last == null

               head = p;        else { 

               p.before = last

               last.after = p;        }        tail = p;        ++modCount;    }} 

    目前,假设运用 LinkedHashMap 做LRU,还有一个成绩困扰着我们,就是假设容量有限,该如何淘汰旧数据?

    我们回过头看看 put 办法

    public V put(K key, V value) { 

        return putVal(hash(key), key, value, falsetrue); 

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { 

        Node<K,V>[] tab; Node<K,V> p; int n, i; 

        if ((tab = table) == null || (n = tab.length) == 0) 

            n = (tab = resize()).length; 

        if ((p = tab[i = (n - 1) & hash]) == null

            tab[i] = newNode(hash, key, value, null); 

        else { 

            Node<K,V> e; K k; 

            if (p.hash == hash && 

                ((k = p.key) == key || (key != null && key.equals(k)))) 

                e = p; 

            else if (p instanceof TreeNode) 

                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); 

            else { 

                for (int binCount = 0; ; ++binCount) { 

                    if ((e = p.next) == null) { 

                        p.next = newNode(hash, key, value, null); 

    (责任编辑:admin)