简体   繁体   English

java中LinkedHashMap中的addEntry方法

[英]the addEntry method in LinkedHashMap in java

Recently I read the source code of LinkedHashmap in java,I know that the linked hashmap use doubly link to restore entry.最近在java中阅读了LinkedHashmap的源码,知道链接的hashmap使用双链恢复入口。 When addEntry ,it will remove the eldest key of the list, but when I read the code, I have some problemaddEntry ,它会删除列表的最年长的键,但是当我阅读代码时,我有一些问题

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.在第 430 行, eldest = header.after ,但我认为列表的末尾不是header.after ,因为header.after是第二个条目。

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. LinkedHashMap的代码随着时间的推移发生了变化,它是 android 的完全不同的代码,所以我不确定那是哪个版本。 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).但是,在我看来,在第一个节点之前和最后一个节点之后有“虚拟”节点是有意义的(这样即使是空的LinkedHashMap也有 2 个节点)。 This way you can remove a node X from the map by getting the nodes before and after X :这样你可以删除节点X通过之前和之后获得的节点从地图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.after之前的新节点设置为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.如果您没有虚拟节点,则X.beforeX.after一个或两个都可能为null ,因此它会使此过程的编码变得更加笨拙。

I have seen versions of LinkedHashMap that use these 2 extra nodes, and other versions that don't.我见过使用这两个额外节点的LinkedHashMap版本,以及其他不使用的版本。 In the version you're looking at , the first and last "dummy" nodes (called header ) are actually the same object reused.您查看版本中,第一个和最后一个“虚拟”节点(称为header )实际上是重用的同一个对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM