【关于List.remove()报错的问题】
我们如果想删掉List中某一个对象,我们可能就会想到会用List.remove()方法。但是这样如果后续操作这个list的时候就会报错。
具体的原因是当你操作了List的remove方法的时候,他回去修改List的modCount属性。导致抛出异常java.util.ConcurrentModificationException。
最好的想要修改List对象,我们可以用ListIterator。就像这样:
ArrayList<Integer> arrayList = new ArrayList<>();
for (int i = 0; i < 20; i++) {
arrayList.add(Integer.valueOf(i));
}
ListIterator<Integer> iterator = arrayList.listIterator();
while (iterator.hasNext()) {
if(需要满足的条件){
iterator.remove();//删除操作
iterator.add(integer);//新增操作
}
}
这样就不会去修改List的modCount属性。