码农小汪-Map遍历的时候删除元素
2016-04-24 21:09
232 查看
今天这里有个需求,需要在遍历Map的时候删除我们的Map中的元素
我自己也是写了一个Demopackage 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); } } }
相关文章推荐
- LintCode——搜索区间
- 程序员菜鸟逆袭,英语学习之路(版本v.1.0)
- LintCode——删除链表中的元素
- 面试题12:打印1到最大的n位数
- 面试题11:数值的整数次方
- 码农小汪-解决java compiler level does not match the version of the installed java project facet
- 2016年3月14日作业
- 面试题
- LintCode 链表求和
- Android面试题——XUtils框架
- 高级程序员的技能
- php面试题及答案收藏(转)
- JAVA面试题:子类无法覆盖父类中的方法
- JAVA面试题---多态成员变量的特点
- 常见面试题-乱序字符串的判断
- 面试:数组:合并区间:058
- 两年工作经验java面试题精炼汇总
- 前端面试资料总结——附上大量优质资料链接
- 软考中高项学员:2016年3月14日作业
- LintCode——岛屿的个数