今天我研究从java.util.HashMap中删除特殊对象.我测试了错误的语法.但我遇到了一个很棒的问题.控制台上的消息不在订单中.异常消息由错误的订单打印.程序似乎是用多线程执行的.以下是我的代码.
package com.study.iter;
import java.util.HashMap;
import java.util.Map;
public class TestRmObjFromMap {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap();
map.put("1", 1);
map.put("2", 2);
map.put("3", 3);
map.put("4", 4);
remove1(map);
}
private static void remove1(Map<String, Integer> map) {
for(Map.Entry<String, Integer> entry : map.entrySet()) {
if(entry.getKey().equals("3")) {
map.remove(entry.getKey());
}
else {
System.out.println("key: " + entry.getKey() + " -- value: " + entry.getValue());
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
运行此代码后,它将打印以下内容:
Exception in thread "main" java.util.ConcurrentModificationException
key: 1 -- value: 1
key: 2 …Run Code Online (Sandbox Code Playgroud)