map遍历删除异常:ConcurrentModificationException
生活随笔
收集整理的這篇文章主要介紹了
map遍历删除异常:ConcurrentModificationException
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1. map集合單個刪除
此時,一般都不會出問題,直接 remove(key)
2. map集合遍歷刪除多個
此時,若不注意往往容易出現(xiàn)問題,出現(xiàn) ConcurrentModificationException
為什么呢?
使用iterator迭代刪除時沒有問題的,在每一次迭代時都會調(diào)用hasNext()方法判斷是否有下一個,是允許集合中數(shù)據(jù)增加和減少的。
使用forEach刪除時,會報錯ConcurrentModificationException,因為在forEach遍歷時,是不允許map元素進(jìn)行刪除和增加。
所以,遍歷刪除map集合中元素時,必須使用迭代iterator
3. 案例
有如下集合:
Map<String, Integer> map=new HashMap<>();map.put("張三",22);map.put("李四",25);map.put("王五",33);map.put("趙六",28);map.put("田七",25);map.put("李思",25);map.put("李嘉欣",25);需求:刪除名字(即key)中包含“李”的元素
使用forEach時:
Set<Entry<String, Integer>> set=map.entrySet();for (Entry<String, Integer> entry : set) {String name=entry.getKey();System.out.println(name);System.out.println(name.contains("李"));if(name.contains("李")){map.remove(name);} }會報如下異常:
使用iterator時,一切正常
特別注意:刪除時不能使用map.remove(key),否則也報ConcurrentModificationException
只能使用iterator.remove
Set<Entry<String, Integer>> set=map.entrySet();Iterator<Entry<String, Integer>> iterator=set.iterator();while(iterator.hasNext()){Entry<String, Integer> entry=iterator.next();String name=entry.getKey();if(name.contains("李")){//特別注意:不能使用map.remove(name) 否則會報同樣的錯誤iterator.remove();} }解釋:Iterator.remove()是刪除最近(最后)使用next()方法的元素。
從迭代器指向的集合中移除迭代器返回的最后一個元素(可選操作)。每次調(diào)用 next 只能調(diào)用一次此方法。
完成代碼:
package map遍歷和刪除;import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set;/*map集合遍歷刪除*/ public class Test2 {public static void main(String[] args) {//key=name value=ageMap<String, Integer> map=new HashMap<>();map.put("張三",22);map.put("李四",25);map.put("王五",33);map.put("趙六",28);map.put("田七",25);map.put("李思",25);map.put("李嘉欣",25);//單個刪除刪--remove map.remove("張三");for(Map.Entry<String, Integer> entry:map.entrySet()){System.out.println(entry.getKey()+"="+entry.getValue());}//需求:刪除名字(即key)中包含“李”的元素/*分析:* 1.此時直接map.remove(key)就不符合要求了,必須進(jìn)行遍歷刪除* * 2.通常map集合遍歷就兩種方式,一個foreach和iterator* */Set<Entry<String, Integer>> set=map.entrySet();/*for (Entry<String, Integer> entry : set) {String name=entry.getKey();System.out.println(name);System.out.println(name.contains("李"));if(name.contains("李")){map.remove(name);}}*/Iterator<Entry<String, Integer>> iterator=set.iterator();while(iterator.hasNext()){Entry<String, Integer> entry=iterator.next(); // String name=entry.getKey();String name=entry.getKey();int value=entry.getValue();if(name.contains("李")){//特別注意:不能使用map.remove(name) 否則會報同樣的錯誤iterator.remove();}}System.out.println();for (Entry<String, Integer> entry : set) {System.out.println("姓名:"+entry.getKey()+",年齡:"+entry.getValue());}} } 《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的map遍历删除异常:ConcurrentModificationException的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oracle层次查询中prior与自上而
- 下一篇: 外键为主键可以重复原因