zoukankan      html  css  js  c++  java
  • 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);  
        }  
    }  
    
  • 相关阅读:
    javascript对话框
    重构之美-走在Web标准化设计的路上[复杂表单]
    xhtml标准下的height:100%
    javascript简洁的LightBox
    Web标准学习书籍推荐
    Email
    jQuery插件Cookie
    Linq to sql 简单性能差异指引 2 (转)
    jQuery Impromptu
    UI
  • 原文地址:https://www.cnblogs.com/cchilei/p/13099203.html
Copyright © 2011-2022 走看看