I am reading LinkedHashMap source code in JDK 11 and I found a piece of dead code(I'm not sure)
As we all know, LinkedHashMap use a doubly linked list to preserve the order of all the elements.It has a member called accessOrder
final boolean accessOrder;
By default it is false, but if it is set to true, everytime you run get, it will move the element it gets to the end of the linked list.That is what the function afterNodeAccess do.
//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;
}
}
So here comes my problem:
(accessOrder && (last = tail) != e means e is not the last node of the linked list. If e is already the last node, we dont have to do anything right?
Then a as the after node of p, (p is e after casting to LinkedHashMap.Entry), it cant be null. Only if p is the last node then a can be null.
So what's the point of the following piece of code?
// 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 always != null , the else clause last = b will never be executed....So is it dead code?
Also I do an experiment with accessorder set as true, then I get the last node in debug mode and it seems that I can't never get into the above else caluse last = b
Any suggestions?