第一次迭代:-
class ConcurrentHashMapBehaviour
{
public static void main(String[] args)
{
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
map.put("ONE", 1);
map.put("TWO", 2);
map.put("THREE", 3);
map.put("FOUR", 4);
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()){
String key = (String) it.next();
System.out.println(key+" : "+map.get(key));
map.put("SEVEN", 7);
}
}
}
输出是:
ONE : 1
FOUR : 4
TWO : 2
THREE : 3
SEVEN : 7
更改 key 后的第二次迭代
class ConcurrentHashMapBehaviour
{
public static void main(String[] args)
{
ConcurrentHashMap<String, Integer> map = new
ConcurrentHashMap<String, Integer>();
map.put("ONE", 1);
map.put("TWO", 2);
map.put("THREE", 3);
map.put("FOUR", 4);
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()){
String key = (String) it.next();
System.out.println(key+" : "+map.get(key));
map.put("FIVE", 5);
}
}
}
输出是:
ONE : 1
FOUR : 4
TWO : 2
THREE : 3
所以我的问题是为什么第一次迭代包含 7 作为输出,但在第二次迭代中不包含 5?
最佳答案
Javadoc(我强调):
Similarly, Iterators, Spliterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration.
换句话说,对于迭代器可用的 View 没有任何保证。在创建 Iterator
之后,它可能会或可能不会意识到映射的更改。唯一的保证是
They do not throw ConcurrentModificationException.
关于Java : In ConcurrentHashMap , 如果我更改 key ,为什么会有不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49358037/