public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<>();
map.put(1,10);
map.put(2,20);
map.put(3,30);
for (Integer i:map.keySet()){
map.put(i+10,map.get(i));
map.remove(i);
}
}
看这段代码,想完成的是在将原先map里的key增加10,value不变,然后移除旧的key,但是程序报错
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(HashMap.java:1442)
at java.util.HashMap$KeyIterator.next(HashMap.java:1466)
at aa.main(aa.java:11)
接着用网上 Iterator 的方法 remove,问题依旧存在。
后来用下面的方法,问题解决
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<>();
map.put(1,10);
map.put(2,20);
map.put(3,30);
System.out.println(map);
Object[] objects = map.keySet().toArray();
for (Object i:objects){
Integer z = (Integer)i;
map.put(z+10,map.get(i));
map.remove(z);
}
System.out.println(map);
}