gpt4 book ai didi

java - java HashMap 的快速失败行为

转载 作者:搜寻专家 更新时间:2023-10-31 19:57:11 25 4
gpt4 key购买 nike

我尝试使用 java.util.HashMap 来了解什么是fail-fast 行为。

HashMap map = new HashMap();
map.put("jon", 10);
map.put("sean", 11);
map.put("jim", 12);
map.put("stark", 13);
map.put("vic", 14);
Set keys = map.keySet();
for(Object k:keys) {
System.out.println(map.get(k));
}

for(Object k:keys) {
String key =(String)k;
if(key.equals("stark")) {
map.remove(key);
}
}

System.out.println("after modifn");
for(Object k:keys) {
System.out.println(map.get(k));
}

我得到了结果

12
11
10
14
13
after modifn
12
11
10
14

我也试过使用迭代器

Iterator<String> itr = keys.iterator();
while(itr.hasNext()) {
String key = itr.next();
if(key.equals("stark")) {
map.remove(key);
}
}

在这两种情况下我都没有得到任何 ConcurrentModificationException ..这是因为(来自 javadoc)

the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis

我检查了另一个 thread它说,它会抛出 ConcurrentModificationException..你怎么看?

最佳答案

鉴于您显示的输出:

12
11
10
14
13 // notice this?
after modifn
12
11
10
14

因为 13 是最后一个键值对,当您 Iterate通过你的HashMap然后最后去掉stark 13对应的key-value ,这会停止 IterationHashMap 之后已被修改,因此,它不会 iterate了。所以没有 ConcurrentModificationException.

关于java - java HashMap 的快速失败行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11094139/

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