gpt4 book ai didi

Java7 WeakHashMap isEmpty() 似乎不对

转载 作者:搜寻专家 更新时间:2023-11-01 01:31:09 24 4
gpt4 key购买 nike

我正在尝试使用 Java7 的 WeakHashMap,我发现它的 isEmpty() 方法给出了错误的结果。

import java.util.Map;
import java.util.WeakHashMap;

public class Test
{

public static void main(final String[] args)
{
final Map<String, Boolean> map = new WeakHashMap<>();

String b = new String("B");
map.put(b, true);
b = null;

System.gc();
System.out.println(map.isEmpty());
System.out.println(map.keySet().isEmpty());
System.out.println(map);
}

}

实际结果:

错误

正确

{}

也就是说,

map.isEmpty() 和 map.keySet().isEmpty() 不一致。有人可以帮我理解吗?非常感谢。

最佳答案

你应该阅读 WeakHashMap 的 javadoc :

The behavior of the WeakHashMap class depends in part upon the actions of the garbage collector, so several familiar (though not required) Map invariants do not hold for this class. Because the garbage collector may discard keys at any time, a WeakHashMap may behave as though an unknown thread is silently removing entries. In particular, even if you synchronize on a WeakHashMap instance and invoke none of its mutator methods, it is possible for the size method to return smaller values over time, for the isEmpty method to return false and then true, for the containsKey method to return true and later false for a given key, for the get method to return a value for a given key but later return null, for the put method to return null and the remove method to return false for a key that previously appeared to be in the map, and for successive examinations of the key set, the value collection, and the entry set to yield successively smaller numbers of elements.

总而言之,您看到的效果是完全有效的。

关于Java7 WeakHashMap isEmpty() 似乎不对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55405864/

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