Reputation: 17
Recently I read the source code of LinkedHashmap
in java,I know that the linked hashmap use doubly link to restore entry. When addEntry
,it will remove the eldest key of the list, but when I read the code, I have some problem
426 addEntry(int hash, K key, V value, int bucketIndex) {
427 super.addEntry(hash, key, value, bucketIndex);
428
429 // Remove eldest entry if instructed
430 Entry<K,V> eldest = header.after;
431 if (removeEldestEntry(eldest)) {
432 removeEntryForKey(eldest.key);
433 }
434 }
in line 430,eldest = header.after
,but I think the end of the list is not header.after
, because header.after
is the second entry.
Upvotes: 2
Views: 342
Reputation: 37645
The code for LinkedHashMap
has changed over time, and it's completely different code for android, so I'm not exactly sure which version that is. However, in my view it makes sense to have "dummy" nodes before the first node and after the last node (so that even an empty LinkedHashMap
has 2 nodes). This way you can remove a node X
from the map by getting the nodes before and after X
:
X.before -> X -> X.after
and setting the new node following X.before
to be X.after
and the new node coming before X.after
to be X.before
.
X.before ------> X.after (X has gone.)
The code for this can simply be:
X.before.after = X.after;
X.after.before = X.before;
If you don't have dummy nodes, either or both of X.before
or X.after
could be null
, so it makes this process slightly more awkward to code.
I have seen versions of LinkedHashMap
that use these 2 extra nodes, and other versions that don't. In the version you're looking at, the first and last "dummy" nodes (called header
) are actually the same object reused.
Upvotes: 2