(轉)Exception in thread "main" java.util.ConcurrentModificationException異常怎麼解決?

【轉載原因:同樣遇到set的foreach遍歷中調用remove方法,導致這個錯誤。】

【轉載原文:https://blog.csdn.net/jdk_wangtaida/article/details/87450334】


版權聲明:本文爲博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。
本文鏈接:https://blog.csdn.net/jdk_wangtaida/article/details/87450334

前言:

出現這個異常,一般就是在遍歷ArrayList刪除元素時會出現這個異常,這篇文章講解下怎麼解決這個問題。

正文:

1.我先復現下出現這個bug的情景,代碼如下

@Data
@AllArgsConstructor
@NoArgsConstructor
class Student {
    private String name;
    private String id;
}
 
class ArrayListDelete {
    public static void main(String[] args) {
        Student student = new Student("小明", "1");
        Student student1 = new Student("小明", "2");
        Student student2 = new Student("小明", "3");
        ArrayList<Student> students = new ArrayList<>();
        students.add(student);
        students.add(student1);
        students.add(student2);
        for (Student s : students) {
            if (s.getId().equals("1")) {
                students.remove(s);
            }
        }
        System.out.println(students.toString());
    }
}

運行這個代碼就會出現文章提到的這個錯誤java.util.ConcurrentModificationException,如下圖

2.出現這個異常的原因是,在對集合ArrayList遍歷時,調用了list.remove()方法,具體原因需要看源碼纔可以理解,源碼分析傳送門:https://blog.csdn.net/androidboy365/article/details/50540202/

3.解決方案就是不要用for-each遍歷,換成迭代器遍歷,並且不要用list.remove()方法移除對象,用迭代器的方法iterator.remove()移除對象,具體看下面的代碼:

class ArrayListDelete {
    public static void main(String[] args) {
        Student student = new Student("小明", "1");
        Student student1 = new Student("小明", "2");
        Student student2 = new Student("小明", "3");
        ArrayList<Student> students = new ArrayList<>();
        students.add(student);
        students.add(student1);
        students.add(student2);
        Iterator<Student> iterator = students.iterator();
        while (iterator.hasNext()){
            Student next = iterator.next();
            if(next.getId().equals("1")){
             iterator.remove();
            }
        }
        System.out.println(students.toString());
    }
}


執行結果,這樣就解決了這個異常ConcurrentModificationException。

總結:

我是阿達,一名喜歡分享知識的程序員,時不時的也會荒腔走板的聊一聊電影、電視劇、音樂、漫畫,這裏已經有六位小夥伴在等你們啦,感興趣的就趕緊來點擊關注我把,哪裏不明白或有不同觀點的地方歡迎留言。
 

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