map循環刪除某個元素


下面代碼展示了遍歷Map時刪除元素的正確方式和錯誤方式。

import java.util.HashMap;  
import java.util.Iterator;  
import java.util.Map;  
import java.util.Set;  
  
 
public class TestMapRemove {  
    public static void main(String[] args){  
        new TestMapRemove().removeByIterator();  
//        new TestMapRemove().removeBymap();  
    }  
    public void removeByIterator(){//正確的刪除方式  
        HashMap<Integer, String> map = new HashMap<Integer, String>();  
        map.put(1, "one");  
        map.put(2, "two");  
        map.put(3, "three");  
        System.out.println(map);  
        Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();  
        while(it.hasNext()){  
            Map.Entry<Integer, String> entry = it.next();  
            if(entry.getKey() == 2)  
                it.remove();//使用迭代器的remove()方法刪除元素  
        }  
        System.out.println(map);  
    }  
    public void removeBymap(){//錯誤的刪除方式  
        HashMap<Integer, String> map = new HashMap<Integer, String>();  
        map.put(1, "one");  
        map.put(2, "two");  
        map.put(3, "three");  
        System.out.println(map);  
        Set<Map.Entry<Integer, String>> entries = map.entrySet();  
        for(Map.Entry<Integer, String> entry : entries){  
            if(entry.getKey() == 2){  
                map.remove(entry.getKey());//ConcurrentModificationException  
            }  
        }  
        System.out.println(map);  
    }  
}  


免責聲明!

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



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