网站首页  汉语字词  英语词汇  考试资料  写作素材  旧版资料

请输入您要查询的考试资料:

 

标题 Java 遍历Map时 删除元素
内容 * 会引发 并发修改异常,可以通过迭代器的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);
    }
    }
    }
随便看

 

在线学习网考试资料包含高考、自考、专升本考试、人事考试、公务员考试、大学生村官考试、特岗教师招聘考试、事业单位招聘考试、企业人才招聘、银行招聘、教师招聘、农村信用社招聘、各类资格证书考试等各类考试资料。

 

Copyright © 2002-2024 cuapp.net All Rights Reserved
更新时间:2025/5/17 20:09:48