異常java.util.ConcurrentModificationException之如何遍歷刪除集合中的元素

異常:java.util.ConcurrentModificationException
       at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
       at java.util.ArrayList$Itr.next(ArrayList.java:851)
       at com.mediwit.illcase.service.impl.CaseIdService.getTreatCompanyList(CaseIdService.java:1237)
       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
       at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

       at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

               ....

原因:出現該異常的原因大多數情況下是在遍歷集合的時候,執行了對集合元素的刪除,如下所示:

 public void test() {
 try {
 ArrayList<String> list = new ArrayList<String>();
 list.add("company1");
 list.add("company2");
 list.add("company3");
 list.add("company4");
 for (String string : list) {
 if(string.equals("company1")) {
 list.remove(string);
 }
 }
 }catch(Exception e) {
 e.printStackTrace();
 }

  }

而集合元素在進行更改的時候會觸發一個   checkForComodification()  方法,方法中有這麼一段代碼:

  if(modCount != exceptedModCount)
        throw new ConcurrentModificationException();
  }

調用list.remove()後導致了modCount!=exceptiedModCount,所有就拋異常了;

解決

使用迭代器遍歷,調用迭代器的刪除方法:如下所示

Iterator<String> it = list.iterator();
     while(it.hasNext()) {

           String curStr = it.next();   

               if("company1".equals(curStr)){

                         it.remove();

                }

     }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章