Java 遍歷Map時 刪除元素


  • 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>();  
  •       
  •    /**  1.HashMap 類映射不保證順序;某些映射可明確保證其順序: TreeMap 類 
  •     *   2.在遍歷Map過程中,不能用map.put(key,newVal),map.remove(key)來修改和刪除元素, 
  •     *   會引發 並發修改異常,可以通過迭代器的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("-------\n\t最終的map的元素遍歷:");  
  •         for(Map.Entry<Integer, String> entry:map.entrySet()){  
  •             int k=entry.getKey();  
  •             String v=entry.getValue();  
  •             System.out.println(k+" = "+v);  
  •         }  
  •     }  


  • 免責聲明!

    本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



     
    粵ICP備18138465號   © 2018-2025 CODEPRJ.COM