当您使用集合对象时,当一个线程在一个特定的集合对象上迭代时,如果您尝试从其中添加或删除元素,则会抛出ConcurrentModificationException。
不仅如此,如果要迭代一个集合对象,请向其添加或删除元素,然后再次尝试对其内容进行迭代,这被认为是您尝试使用多个线程访问该集合对象,并且抛出了ConcurrentModificationException。
import java.util.ArrayList;
import java.util.Iterator;
public class OccurenceOfElements {
public static void main(String args[]) {
ArrayList <String> list = new ArrayList<String>();
//实例化ArrayList对象
list.add("JavaFX");
list.add("Java");
list.add("WebGL");
list.add("OpenCV");
System.out.println("Contents of the array list (first to last): ");
Iterator<String> it = list.iterator();
while(it.hasNext()) {
System.out.print(it.next()+", ");
}
//list.remove(3);
list.add(3, "Hadoop");
while(it.hasNext()) {
System.out.print(it.next()+", ");
}
}
}
输出结果
Contents of the array list (first to last):
JavaFX, Java, WebGL, OpenCV, Exception in thread "main"
java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at sample.OccurenceOfElements.main(OccurenceOfElements.java:23)
要在从多个线程访问集合对象时解决此问题,请使用同步块或方法;如果要在检索数据时修改数据,请在修改数据后再次获取Iterator对象。
import java.util.ArrayList;
import java.util.Iterator;
public class OccurenceOfElements {
public static void main(String args[]) {
ArrayList <String> list = new ArrayList<String>();
//实例化ArrayList对象
list.add("JavaFX");
list.add("Java");
list.add("WebGL");
list.add("OpenCV");
System.out.println("Contents of the array list (first to last): ");
Iterator<String> it = list.iterator();
while(it.hasNext()) {
System.out.print(it.next()+". ");
}
list.remove(3);
System.out.println("");
System.out.println("Contents of the array list after removal: ");
it = list.iterator();
while(it.hasNext()) {
System.out.print(it.next()+". ");
}
}
}
输出结果
Contents of the array list (first to last):
JavaFX. Java. WebGL. OpenCV.
Contents of the array list after removal:
JavaFX. Java. WebGL.