它是JDK11中LinkedHashMap中的死代码吗?
我正在阅读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已经是最后一个节点,我们不必做任何正确的事情?
然后作为 p 的后节点(p 在转换为 LinkedHashMap.Entry 后为 e),它不能为空。仅当 是最后一个节点时,才能为空。a
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
总是,else 子句将永远不会被执行。...那么它是死代码吗?!= null
last = b
另外,我用设置为做一个实验,然后我是调试模式下的最后一个节点,似乎我永远无法进入上述其他caluseaccessorder
true
get
last = b
有什么建议吗?