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("-------\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()不會有問題。


免責聲明!

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



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