gpt4 book ai didi

java - LinkedHashMap.removeEldestEntry 有什么用?

转载 作者:IT老高 更新时间:2023-10-28 20:38:44 27 4
gpt4 key购买 nike

我知道这个问题的答案很容易在互联网上找到。我需要知道如果我选择不removeEldestEntry 会发生什么。以下是我的代码:

package collection;

import java.util.*;

public class MyLinkedHashMap {

private static final int MAX_ENTRIES = 2;

public static void main(String[] args) {
LinkedHashMap lhm = new LinkedHashMap(MAX_ENTRIES, 0.75F, false) {

protected boolean removeEldestEntry(Map.Entry eldest) {
return false;
}
};
lhm.put(0, "H");
lhm.put(1, "E");
lhm.put(2, "L");
lhm.put(3, "L");
lhm.put(4, "O");

System.out.println("" + lhm);

}
}

即使我不允许 removeEldestEntry 我的代码工作正常。那么,内部发生了什么?

最佳答案

removeEldestEntry 总是在插入元素后进行检查。例如,如果您重写该方法始终返回 true,则 LinkedHashMap 将始终为空,因为在每次 putputAll 插入之后,最旧的元素将被删除,不会有什么关系。 JavaDoc 展示了一个关于如何使用它的非常明智的示例:

protected boolean removeEldestEntry(Map.Entry eldest){
return size() > MAX_SIZE;
}

在另一种方式中,您可能只想删除不重要的条目:

protected boolean removeEldestEntry(Map.Entry eldest){
if(size() > MAX_ENTRIES){
if(isImportant(eldest)){
//Handle an important entry here, like reinserting it to the back of the list
this.remove(eldest.getKey());
this.put(eldest.getKey(), eldest.getValue());
//removeEldestEntry will be called again, now with the next entry
//so the size should not exceed the MAX_ENTRIES value
//WARNING: If every element is important, this will loop indefinetly!
} else {
return true; //Element is unimportant
}
return false; //Size not reached or eldest element was already handled otherwise
}

关于java - LinkedHashMap.removeEldestEntry 有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20772869/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com