Java 遍历Map时 删除元素
来源:互联网 发布:n卡负优化a卡战未来 编辑:程序博客网 时间:2024/06/10 11:22
- public class HashMapTest {
- 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("-------\n\t最终的map的元素遍历:");
- for(Map.Entry<Integer, String> entry:map.entrySet()){
- int k=entry.getKey();
- String v=entry.getValue();
- System.out.println(k+" = "+v);
- }
- }
- }
0 0
- java 遍历map时删除元素
- java遍历Map时remove删除元素
- java遍历Map时remove删除元素
- java 遍历map时删除元素
- Java 遍历Map时 删除元素
- Java 遍历Map时 删除元素
- Java 遍历Map时 删除元素
- Java 遍历Map时 删除元素
- Java 遍历Map时 删除元素
- Java中遍历Map时删除元素的方法
- Java 遍历Map时 删除元素ZZ
- java 遍历map同时删除元素
- Java Map遍历过程中删除元素
- Map遍历与删除元素
- Java Map在遍历过程中删除元素
- Java Map遍历的同时进行元素删除
- Java Map在遍历过程中删除元素
- java.util.ConcurrentModificationException---用迭代器遍历Map时删除其中元素出现异
- c#栈队列的实现和应用
- ubuntu mysql 安装和外网访问配置
- SQL Server中的Merge关键字
- thinkphp的select和find的区别
- 第十三周项目5---拓扑排序算法验证
- Java 遍历Map时 删除元素
- Mybatis的<where><trim><set>标签使用和排重
- 线性表-双向链表
- Book1-Unit5
- Java-值传递or引用传递
- SSM问题1:Error configuring application listener of class org.springframework.web.context.ContextLoader
- Python 中requests 模块text 和content 差别
- Book2-Unit1
- jQuery UI 实例 - 对话框(Dialog)