Java 遍历Map时 删除元素


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值