出现这个错误一般是在迭代时使用了集合对象的方法操作集合中的元素,出现的并发修改异常,因为在使用迭代器时,只能用迭代器的方法操作元素。
//使用Iterator遍历输出
Iterator<String> it = list.iterator();
while(it.hasNext()){
String string = it.next()
if(string.equals("gggg"));
/*此处使用的是集合对象的方法对集合进行添加
所以会报并发修改异常*/
list.add("This Is Wrong!");
}
System.out.println(list);
但是Iterator中的方法很有限,只有判断,查询和删除,如果想要实现其他的操作(添加,修改等),需要使用Iterator的子接口ListIterator来完成迭代中集合的增删改查(只有List元素能使用此方法,因为list元素都自带角标)所以这里应该使用ListIterator
//使用ListIterator遍历输出
ListIterator<String> it = list.listIterator();
while(it.hasNext()){
String string = it.next();
if(string.equals("gggg"))
it.add("Tis Is Right!");
/*此处使用的是集合对象的方法对集合进行添加
所以会报并行修改异常*/
//list.add("This Is Wrong!");
}