场景
很常见的场景,有一组集合,需要遍历集合,然后去掉集合里面的多个对象。
现象
当调用iterator的remove方法时,报出了异常"UnsupportedOperationException"。
原因分析
打断点对源码进行调试,发现遍历的集合类是Arrays.ArrayList类,继续跟踪,发现remove方法并没有覆盖AbstractList的remove方法,所以调用remove方法的时候直接抛出了一个UnsupportedOperationException异常.
//AbstractList内的remove方法
public E remove(int index) {
throw new UnsupportedOperationException();
}
//iterator的remove方法
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
//实际调用的remove方法
AbstractList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}