方法一:
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进行操作才可以
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步