在JAVA的集合(LIST,SET)中通過iterator.hasNext() 或者iterator.next()遍曆集合中的資料時,如果這時候add或者remove集合中的元素,會發生ConcurrentModificationException異常.
本文簡單說明一下這種現象和解決方案.
如下面的代碼,不管是remove還是add都會發生ConcurrentModificationException異常.
public static void testWrongAccess2() { Collection<String> myCollection = new ArrayList<String>(10); myCollection.add("1"); myCollection.add("2"); myCollection.add("3"); myCollection.add("4"); Iterator itr = myCollection.iterator(); while (itr.hasNext()) { String myObject = (String) itr.next(); System.out.println(myObject); if ("2".equals(myObject)) { myCollection.remove(myObject); // cause ConcurrentModificationException //myCollection.add("4"); // cause ConcurrentModificationException } } }//1.5之後的寫法也是會有異常的 for (String myObject: myCollection) { System.out.println(myObject); if ("2".equals(myObject)) { myCollection.remove(myObject); } }
關於remove的解決辦法是:利用iterator的remove方法.
public static void testRightAccess() {Collection<String> myCollection = new ArrayList<String>(10);myCollection.add("1");myCollection.add("2");myCollection.add("3");myCollection.add("4");Iterator itr = myCollection.iterator(); while (itr.hasNext()) {String myObject = (String) itr.next();System.out.println(myObject);if ("2".equals(myObject)) {itr.remove();}}}
對於在集合滿足某種條件的情況下add元素的解決:先將要add的元素放在另外一個集合裡,在判斷遍曆完成後在加入.
public static void testRightAccess2() {Collection<String> myCollection = new ArrayList<String>(10);myCollection.add("1");myCollection.add("2");myCollection.add("3");myCollection.add("4");Collection<String> tempCollection = new ArrayList<String>(10);Iterator itr = myCollection.iterator(); while (itr.hasNext()) {String myObject = (String) itr.next();if ("1".equals(myObject)) {tempCollection.add("1 Exists");}if ("2".equals(myObject)) {tempCollection.add("2 Exists");}}myCollection.addAll(tempCollection);}
這裡碰到一個有趣的現象:下面的代碼沒有發生ConcurrentModificationException,在一個只有3個元素的集合中,remove第二個元素,沒有ConcurrentModificationException發生而且最後集合裡只有1和3,remove 1 和 3 都會有異常,add元素也會有異常,難道是JDK的bug??總之,在remove元素的時候應該用iterator的remove方法.
public static void testWrongAccess1() {Collection<String> myCollection = new ArrayList<String>(10);myCollection.add("1");myCollection.add("2");myCollection.add("3");Iterator itr = myCollection.iterator(); while (itr.hasNext()) {String myObject = (String) itr.next();System.out.println(myObject);if ("2".equals(myObject)) {myCollection.remove(myObject); // doesn't cause ConcurrentModificationException//myCollection.add("4"); // cause ConcurrentModificationException}}}