Java Map在遍历过程中删除元素

逃离我推掉我的手 2024-04-17 16:08 174阅读 0赞

Java中的Map如果在遍历过程中要删除元素,除非通过迭代器自己的remove()方法,否则就会导致抛出ConcurrentModificationException异常。

JDK文档中是这么描述的:
The iterators returned by all of this class’s “collection view methods” are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

这么做的原因是为了保证迭代器能够尽快感知到Map的“结构性修改“,从而避免不同视图下不一致现象。

下面代码展示了遍历Map时删除元素的正确方式和错误方式。

  1. import java.util.HashMap;
  2. import java.util.Iterator;
  3. import java.util.Map;
  4. import java.util.Set;
  5. /**
  6. * Created by lh on 15-1-22.
  7. */
  8. public class TestMapRemove {
  9. public static void main(String[] args){
  10. new TestMapRemove().removeByIterator();
  11. // new TestMapRemove().removeBymap();
  12. }
  13. public void removeByIterator(){//正确的删除方式
  14. HashMap<Integer, String> map = new HashMap<Integer, String>();
  15. map.put(1, "one");
  16. map.put(2, "two");
  17. map.put(3, "three");
  18. System.out.println(map);
  19. Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
  20. while(it.hasNext()){
  21. Map.Entry<Integer, String> entry = it.next();
  22. if(entry.getKey() == 2)
  23. it.remove();//使用迭代器的remove()方法删除元素
  24. }
  25. System.out.println(map);
  26. }
  27. public void removeBymap(){//错误的删除方式
  28. HashMap<Integer, String> map = new HashMap<Integer, String>();
  29. map.put(1, "one");
  30. map.put(2, "two");
  31. map.put(3, "three");
  32. System.out.println(map);
  33. Set<Map.Entry<Integer, String>> entries = map.entrySet();
  34. for(Map.Entry<Integer, String> entry : entries){
  35. if(entry.getKey() == 2){
  36. map.remove(entry.getKey());//ConcurrentModificationException
  37. }
  38. }
  39. System.out.println(map);
  40. }
  41. }

发表评论

表情:
评论列表 (有 0 条评论,174人围观)

还没有评论,来说两句吧...

相关阅读