码农小汪-Map遍历的时候删除元素
来源:互联网 发布:开山刀淘宝哪里有卖 编辑:程序博客网 时间:2024/05/17 01:28
今天这里有个需求,需要在遍历Map的时候删除我们的Map中的元素
我自己也是写了一个Demo
package test;import java.util.HashMap;import java.util.Map;public class Test { public static void main(String[] args) { Map<Integer, Integer> map= new HashMap<Integer, Integer>(); map.put(1, 1); map.put(2, 1); map.put(3, 1); map.put(4, 1); map.put(5, 1); for(Integer key : map.keySet()){ if(key==1){ map.remove(key); } System.out.println(key+" "); } }}Exception in thread "main" java.util.ConcurrentModificationException at java.util.HashMap$HashIterator.nextNode(HashMap.java:1429) at java.util.HashMap$KeyIterator.next(HashMap.java:1453) at test.Test.main(Test.java:14)
出现了这个错,好像是不可以哦~~!哈哈
那么换一种方式: 这种方式是可以的哦,利用迭代器删除!
package test;import java.util.HashMap;import java.util.Iterator;import java.util.Map;public class test2 { private static Map<Integer, String> map=new HashMap<Integer,String>(); /** 1.HashMap 类映射不保证顺序;某些映射可明确保证其顺序: TreeMap 类 * 2.在遍历Map过程中,不能用map.put(key,newVal),map.remove(key)来修改和删除元素, * 会引发 并发修改异常,可以通过迭代器的remove(): * 从迭代器指向的 collection 中移除当前迭代元素 * 来达到删除访问中的元素的目的。 * */ public static void main(String[] args) { map.put(1,"one"); map.put(2,"two"); map.put(3,"three"); map.put(4,"four"); map.put(5,"five"); map.put(6,"six"); map.put(7,"seven"); map.put(8,"eight"); map.put(5,"five"); map.put(9,"nine"); map.put(10,"ten"); Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator(); while(it.hasNext()){ Map.Entry<Integer, String> entry=it.next(); int key=entry.getKey(); if(key%2==1){ System.out.println("delete this: "+key+" = "+key); //map.put(key, "奇数"); //ConcurrentModificationException //map.remove(key); //ConcurrentModificationException it.remove(); //OK } } //遍历当前的map;这种新的for循环无法修改map内容,因为不通过迭代器。 System.out.println("-------nt最终的map的元素遍历:"); for(Map.Entry<Integer, String> entry:map.entrySet()){ int k=entry.getKey(); String v=entry.getValue(); System.out.println(k+" = "+v); } }}
0 0
- 码农小汪-Map遍历的时候删除元素
- c++ 遍历map的时候删除元素
- 遍历删除map中元素的方法
- map的遍历及删除元素
- Map遍历与删除元素
- list遍历的时候,删除某个符合条件的元素
- List遍历的时候将其中的元素删除掉
- list遍历的时候,删除某个符合条件的元素
- List在遍历时候的删除元素问题
- 在遍历集合的时候删除集合中的元素
- java 为什么遍历的时候不能删除元素
- Java中遍历Map时删除元素的方法
- Java Map遍历的同时进行元素删除
- map容器(元素的添加/遍历/删除)
- 遍历map时删除不需要的元素方法
- Map遍历的两种方式(首推entrySet())--遍历Map时删除元素的方法
- std::map遍历删除某些元素问题
- java 遍历map时删除元素
- maven打包时跳过测试
- word2013设置无格式粘贴快捷方式
- noip2014解方程(真不知道那些大神怎么想到取模的,竟然考这个?!)
- spring源码剖析(二)Spring默认标签解析及注册实现
- tcp协议单用户图片上传
- 码农小汪-Map遍历的时候删除元素
- Matlab一个计算不同拉普拉斯矩阵的小函数
- HTML中的列表和表格
- Java 异常处理机制
- 对于ios7.0以后的截屏功能
- 课程练习二-1016-Red and Black
- CSS3中的变形与动画(下)
- Java基础
- Android开发之WebView组件的使用解析