理解和解決Java併發修改異常ConcurrentModificationException(轉載)

原文地址:https://www.jianshu.com/p/f3f6b12330c1

理解和解決Java併發修改異常ConcurrentModificationException

不知讀者在Java開發的過程當中有沒有遇到相似的異常信息 Exception in thread "main" java.util.ConcurrentModificationException, 下面小編簡單介紹異常緣由以及這種異常的改進方法,內容很簡單,有什麼問題還望指正。java

假設咱們要實現這樣一個例子: 判斷集合裏面有沒有"world"這個元素,若是有,就添加一個"javaee"元素併發

出現異常的代碼以下:ui

import java.util.ArrayList; import java.util.Iterator; public class Test { public static void main(String[] args) { ArrayList<String> array = new ArrayList<String>(); // 建立並添加元素 array.add("hello"); array.add("world"); array.add("java"); Iterator it = array.iterator(); while (it.hasNext()) { String s = (String) it.next(); if ("world".equals(s)) { array.add("javaee"); } } } } 

1.異常解釋spa

  • ConcurrentModificationException:當方法檢測到對象的併發修改,但不容許這種修改時,拋出此異常。
  • 產生的緣由:
    迭代器是依賴於集合而存在的,在判斷成功後,集合的中新添加了元素,而迭代器殊不知道,因此就報錯了,這個錯叫併發修改異常。
    簡單描述就是:迭代器遍歷元素的時候,經過集合是不能修改元素的。
  • 如何解決呢?
    A:迭代器迭代元素,迭代器修改元素
    B:集合遍歷元素,集合修改元素(普通for)

2.下面用兩種方法去解決這個異常code

import java.util.ArrayList; public class Test { public static void main(String[] args) { ArrayList<String> array = new ArrayList<String>(); // 建立並添加元素 array.add("hello"); array.add("world"); array.add("java"); // 方式1:迭代器迭代元素,迭代器修改元素 // 而Iterator迭代器卻沒有添加功能,因此咱們使用其子接口ListIterator // ListIterator lit = array.listIterator(); // while (lit.hasNext()) { // String s = (String) lit.next(); // if ("world".equals(s)) { // lit.add("javaee"); // } // } // System.out.println("list1:" + array); // 方式2:集合遍歷元素,集合修改元素(普通for) for (int x = 0; x < array.size(); x++) { String s = (String) array.get(x); if ("world".equals(s)) { array.add("javaee"); } } System.out.println("list2:" + array); // 方式3:加強for循環 // 加強for循環寫的話會報一樣的錯誤,由於它自己就是用來替代迭代器的 // for (String s : array) { // if ("world".equals(s)) { // array.add("javaee"); // } // } // System.out.println("list3:" + array); } } 

贈人玫瑰,手有餘香。對象

相關文章
相關標籤/搜索