zoukankan      html  css  js  c++  java
  • Java 遍历Map时 删除元素

    1. package net.nie.test;  
    2.   
    3. import java.util.HashMap;  
    4. import java.util.Iterator;  
    5. import java.util.Map;  
    6.   
    7. public class HashMapTest {  
    8.    private static Map<Integer, String> map=new HashMap<Integer,String>();  
    9.       
    10.    /**  1.HashMap 类映射不保证顺序;某些映射可明确保证其顺序: TreeMap 类 
    11.     *   2.在遍历Map过程中,不能用map.put(key,newVal),map.remove(key)来修改和删除元素, 
    12.     *   会引发 并发修改异常,可以通过迭代器的remove(): 
    13.     *   从迭代器指向的 collection 中移除当前迭代元素 
    14.     *   来达到删除访问中的元素的目的。   
    15.     *   */   
    16.    public static void main(String[] args) {  
    17.         map.put(1,"one");  
    18.         map.put(2,"two");  
    19.         map.put(3,"three");  
    20.         map.put(4,"four");  
    21.         map.put(5,"five");  
    22.         map.put(6,"six");  
    23.         map.put(7,"seven");  
    24.         map.put(8,"eight");  
    25.         map.put(5,"five");  
    26.         map.put(9,"nine");  
    27.         map.put(10,"ten");  
    28.         Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();  
    29.         while(it.hasNext()){  
    30.             Map.Entry<Integer, String> entry=it.next();  
    31.             int key=entry.getKey();  
    32.             if(key%2==1){  
    33.                 System.out.println("delete this: "+key+" = "+key);  
    34.                 //map.put(key, "奇数");   //ConcurrentModificationException  
    35.                 //map.remove(key);      //ConcurrentModificationException  
    36.                 it.remove();        //OK   
    37.             }  
    38.         }  
    39.         //遍历当前的map;这种新的for循环无法修改map内容,因为不通过迭代器。  
    40.         System.out.println("------- 最终的map的元素遍历:");  
    41.         for(Map.Entry<Integer, String> entry:map.entrySet()){  
    42.             int k=entry.getKey();  
    43.             String v=entry.getValue();  
    44.             System.out.println(k+" = "+v);  
    45.         }  
    46.     }  
    47. }  

    基本类型,不会有异常。

    List 在

    (1). 使用索引遍历的时候删除不会有异常,但是后续的数据可能会有问题;

    (2). List用增强的for循环遍历时:会报告异常java.util.ConcurrentModificationException

    (删除完立马break的除外)

    (3). 迭代器迭代时,使用迭代器iterator.remove()不会有问题。

  • 相关阅读:
    hdu2138(求素数)
    hdu2104
    poj1664(放苹果)
    数塔问题给你有哪些启示?
    汉诺塔问题(1)
    算法的力量(转李开复)
    最长子序列问题之系列一
    forward和redirect的区别
    group by 和having
    java中的多态三要素是什么?
  • 原文地址:https://www.cnblogs.com/dongrilaoxiao/p/6676482.html
Copyright © 2011-2022 走看看