java:遍历删除hashmap中的元素

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LUFANGBO/article/details/79484018

方法一:
HashMap<String, Integer> myHashMap = new HashMap<>();
myHashMap.put("1", 1);
myHashMap.put("2", 2);
for (Map.Entry<String, Integer> item : myHashMap.entrySet()){ myHashMap.remove(item.getKey());}
myHashMap.remove(item.getKey());
}

运行上面的代码,Java抛出了java.util.ConcurrentModificationException 的异常,上述方法肯定不行,原因是java中List,set,map类型在遍历时不允许修改元素

方法二:

Iterator<Map.Entry<String, Integer>> it = myHashMap.entrySet().iterator();
while(it.hasNext()){
    Map.Entry<String, Integer> item = it.next();

    if(item满足某个条件){myHashMap.remove(item.getKey());}

}

方法二也是一样会报错。

方法三:

Iterator<Map.Entry<String, Integer>> it = myHashMap.entrySet().iterator();
while(it.hasNext()){
    Map.Entry<String, Integer> item = it.next();

    if(item满足某个条件){it.remove();}

}

方法三ok,remove的时候只能对迭代器遍历it进行操作才可以



猜你喜欢

转载自blog.csdn.net/LUFANGBO/article/details/79484018