Java 遍曆Map時 刪除元素

來源:互聯網
上載者:User

標籤:pac   remove   word   put   內容   修改   string   net   for迴圈   

  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("-------\n\t最終的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()不會有問題。

Java 遍曆Map時 刪除元素

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.