gpt4 book ai didi

java - 弱 HashMap 示例

转载 作者:IT老高 更新时间:2023-10-28 20:49:18 31 4
gpt4 key购买 nike

我创建一个 WeakHashMap 为

WeakHashMap<Employee,String> map = new WeakHashMap<Employee,String>();
map.put(emp,"hello");

其中 emp 是一个 Employee 对象。现在,如果我执行 emp = null 或说不再引用 emp 对象,那么该条目是否会从 WeakHashMap 中删除,即 Map 的大小是否为零?
在HashMap的情况下会反之吗?
我对 WeakHashMap 的理解正确吗?

最佳答案

一个非常简单的例子,启发已经说过的内容:

import java.util.WeakHashMap;

public class WeakHashMapDemo {

public static void main(String[] args) {
// -- Fill a weak hash map with one entry
WeakHashMap<Data, String> map = new WeakHashMap<Data, String>();
Data someDataObject = new Data("foo");
map.put(someDataObject, someDataObject.value);
System.out.println("map contains someDataObject ? " + map.containsKey(someDataObject));

// -- now make someDataObject elligible for garbage collection...
someDataObject = null;

for (int i = 0; i < 10000; i++) {
if (map.size() != 0) {
System.out.println("At iteration " + i + " the map still holds the reference on someDataObject");
} else {
System.out.println("somDataObject has finally been garbage collected at iteration " + i + ", hence the map is now empty");
break;
}
}
}

static class Data {
String value;
Data(String value) {
this.value = value;
}
}
}

输出:

    map contains someDataObject ? true
...
At iteration 6216 the map still holds the reference on someDataObject
At iteration 6217 the map still holds the reference on someDataObject
At iteration 6218 the map still holds the reference on someDataObject
somDataObject has finally been garbage collected at iteration 6219, hence the map is now empty

关于java - 弱 HashMap 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10599710/

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