1. 在使用迭代器遍历时, 使用map 的remove(Object) 方法会抛异常,上个简单粗暴的例子
public static void main(String[] args) {
Map<String,String> map = new HashMap<>();
map.put("name","lion");
map.put("age","18");
map.put("cat","hua");
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String, String> tem = it.next();
if(tem.getKey().equals("name")){
// it.remove();
map.remove(tem.getKey());
}
}
System.out.println(map);
}
报错如下
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(HashMap.java:1473)
at java.util.HashMap$EntryIterator.next(HashMap.java:1507)
at java.util.HashMap$EntryIterator.next(HashMap.java:1505)
a