如何在Map 遍历过程中,删除一个元素?
package ee; import java.util.HashMap; import java.util.Iterator; public class Demo { public static void main(String[] args) { HashMap<Integer, Integer> count = new HashMap<Integer, Integer>(); count.put(1,11); count.put(2,22); count.put(3,33); //错误的 会抛出异常 ----ConcurrentModificationException /* for (Integer i : count.keySet()) { if(i == 2){ count.remove(i); } System.out.println(i); }*/ //正确的 it.remove(); // 这个可以实现 遍历的过程中删除某个元素 Iterator<Integer> it = count.keySet().iterator(); while(it.hasNext()) { Integer key = it.next(); if(key == 2){ it.remove(); // 这个可以实现 遍历的过程中删除某个元素 } if(key == 3){ count.put(key, 44); } } for (Integer value : count.values()) { System.out.println(value); } } }
参考文档:
https://www.cnblogs.com/cherish010/p/9178085.html
https://blog.csdn.net/u011517841/article/details/82955498
posted on 2021-07-27 09:58 William_Dai 阅读(1935) 评论(0) 编辑 收藏 举报