Java 遍历Map时 删除元素ZZ
2017-06-23 00:00
387 查看
http://niewj.iteye.com/blog/1469161
package net.nie.test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HashMapTest {
private static Map map=new HashMap();
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> it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry entry=it.next();
int key=entry.getKey();
if(key%2==1){
System.out.println("delete this: "+key+" = "+key);
//map.put(key, "奇数"); //ConcurrentModificationEx ception
//map.remove(key); //ConcurrentModificationEx ception
it.remove(); //OK
}
}
//遍历当前的map;这种新的for循环无法修改map内容,因为不通过迭代器。
System.out.println("-------\n\t最终的map的元素遍历:");
for(Map.Entry entry:map.entrySet()){
int k=entry.getKey();
String v=entry.getValue();
System.out.println(k+" = "+v);
}
}
}
package net.nie.test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HashMapTest {
private static Map map=new HashMap();
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> it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry entry=it.next();
int key=entry.getKey();
if(key%2==1){
System.out.println("delete this: "+key+" = "+key);
//map.put(key, "奇数"); //ConcurrentModificationEx ception
//map.remove(key); //ConcurrentModificationEx ception
it.remove(); //OK
}
}
//遍历当前的map;这种新的for循环无法修改map内容,因为不通过迭代器。
System.out.println("-------\n\t最终的map的元素遍历:");
for(Map.Entry entry:map.entrySet()){
int k=entry.getKey();
String v=entry.getValue();
System.out.println(k+" = "+v);
}
}
}
相关文章推荐
- Java 遍历Map时 删除元素ZZ 分类: Android资源 2014-05-30 10:59 74人阅读 评论(0) 收藏
- Java 遍历Map时 删除元素ZZ
- java遍历Map时remove删除元素
- java 遍历map时删除元素
- Java 遍历Map时 删除元素
- Java 遍历Map时 删除元素
- java遍历Map时remove删除元素
- Java 遍历Map时 删除元素
- Java 遍历Map时 删除元素
- Java遍历时删除List、Set、Map中的元素(源码分析)
- Java 遍历Map时 删除元素
- java.util.ConcurrentModificationException---用迭代器遍历Map时删除其中元素出现异
- Java 遍历Map时 删除元素
- Java Map遍历过程中删除元素
- java遍历Map时remove删除元素
- java遍历map并删除元素时,使用不当会抛弃异常
- 编程技巧系列(2)Java 集合(List,Set,Map)遍历时有条件删除特定元素
- java遍历Map时remove删除元素
- 【Java】集合(List、Set、Map)遍历、删除、比较元素时的小陷阱
- Java遍历时删除List、Set、Map中的元素(源码分析)