欢迎来到山村网

Java 遍历Map时 删除元素

2019-03-02 09:54:29浏览:194 来源:山村网   
核心摘要:package net.nie.test;import java.util.HashMap;import java.util.Iterator;import java.util.Map;public class HashMapTest {
package net.nie.test;import java.util.HashMap;import java.util.Iterator;import java.util.Map;public class HashMapTest {   private static Map<Integer, String> map=new HashMap<Integer,String>();           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);        }    }}
(责任编辑:豆豆)
下一篇:

Java 将批量的gbk的乱码文件转换到utf8

上一篇:

Java继承结构中类的初始化

  • 信息二维码

    手机看新闻

  • 分享到
打赏
免责声明
• 
本文仅代表作者个人观点,本站未对其内容进行核实,请读者仅做参考,如若文中涉及有违公德、触犯法律的内容,一经发现,立即删除,作者需自行承担相应责任。涉及到版权或其他问题,请及时联系我们 xfptx@outlook.com