是JDK11中LinkedHashMap中的无效代码吗?

问题描述 投票:11回答:1

我正在阅读JDK 11中的LinkedHashMap源代码,但发现了一段无效代码(不确定)

众所周知,LinkedHashMap使用双向链接列表来保留所有元素的顺序。它具有一个名为accessOrder的成员>

final boolean accessOrder;

默认情况下为false,但是如果将其设置为true,则每次运行get时,它将把它到达的元素移到链接列表的末尾。这就是函数afterNodeAccess的作用。

//if accessOrder were set as true, after you visit node e, if e is not the end node of the linked list,
//it will move the node to the end of the linkedlist. 
    void afterNodeAccess(Node<K, V> e) {
        LinkedHashMap.Entry<K, V> last;

        if(accessOrder && (last = tail) != e) {

            //if enter `if` ,it indicates that e is not the end of the linked list, because (last=tail!=e)
            //then `a` as the after node of p(p is e after casting to LinkedHashMap.Entry) is never gonna be null. Only if p is last node of the linked list then a will be null.
            LinkedHashMap.Entry<K, V> p = (LinkedHashMap.Entry<K, V>) e, b = p.before, a = p.after;

            p.after = null;

            if(b == null) {
                head = a;
            } else {
                b.after = a;
            }

            // Is the if else clasue redundant? `a` must not be null.. the else clase will never be excuted.
            if(a != null) {
                a.before = b;
            } else {
                last = b;
            }

            if(last == null) {
                head = p;
            } else {
                p.before = last;
                last.after = p;
            }

            tail = p;

            ++modCount;
        }
    }

所以这就是我的问题:

(accessOrder && (last = tail) != e表示e不是链接列表的最后一个节点。如果e已经是最后一个节点,我们不必做任何事情对吗?

然后a作为p的后节点,(p转换为LinkedHashMap.Entry后为e),不能为null。仅当p是最后一个节点时,a才能为空。

那么下面的代码有什么意义?

 // Is the if else clasue redundant? `a` must not be null.. the else clase will never be excuted.
            if(a != null) {
                a.before = b;
            } else {
                last = b;
            }

[a始终为!= null,else子句last = b将永远不会执行...。那么它是无效代码吗?

[我也进行了一个实验,将accessorder设置为true,然后我get在调试模式下最后一个节点,看来我永远也无法进入上述其他原因last = b

有什么建议吗?

我正在阅读JDK 11中的LinkedHashMap源代码,但发现了一段无效代码(我不确定)。众所周知,LinkedHashMap使用双链表来保留所有元素的顺序。它具有.. 。

java java-8 java-11 linkedhashmap
1个回答
0
投票

OP中提供的代码是用于单个链接列表的节点删除算法,该算法将删除的节点设置为列表的尾部(重新定位为尾部):

© www.soinside.com 2019 - 2024. All rights reserved.