Java 遍历Map时 删除元素

时间:2021-02-01 16:45:58
Java代码  Java 遍历Map时 删除元素
  1. package,,,,,,,,,,,==){
  2. System.out.println("delete this: "+key+" = "+key);
  3. //map.put(key, "奇数");   //ConcurrentModificationException
  4. //map.remove(key);      //ConcurrentModificationException
  5. it.remove();        //OK
  6. }
  7. }
  8. //遍历当前的map;这种新的for循环无法修改map内容,因为不通过迭代器。
  9. System.out.println("-------\n\t最终的map的元素遍历:");
  10. for(Map.Entry<Integer, String> entry:map.entrySet()){
  11. int k=entry.getKey();
  12. String v=entry.getValue();
  13. System.out.println(k+" = "+v);
  14. }
  15. }
  16. }