今天去面试了下,先总结面试的问题吧,然后在继续复习集合,今天遇到个比较模糊的问题,对于我来说
1.list中删除元素
当时面试的时候我回答出在foreach中不可以删除元素,会出现异常,用迭代器的方式可以在循环中删除,当面试官问我为什么会报错的原因:我说删除元素的时候索引会有问(这点不正确),之后回来查资料,正确的回答应该是:在for中是可以删除元素(不过会有问题的,后面的所有元素索引都会前移,此时for循环的指针却会下移,因此会略过下一个元素,解决方案是删除时将指针回调一次),foreach不支持删除,因为当我们把foreach循环反编译之后是一个do while循环,类似迭代器的,删除完成后size的数量减1,但是cursor并没有变化。导致下一次循环不相等继续向下执行,导致检查数组不通过,抛出java.util.ConcurrentModificationException,或者是删除之后直接break就没问题,又或者是用copyonwritelist,因为copyonwritelist重写的remove方法。
----ArrayList
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
----copyonwritelist
public boolean remove(Object o) {
Object[] snapshot = getArray();
int index = indexOf(o, snapshot, 0, snapshot.length);
return (index < 0) ? false : remove(o, snapshot, index);
}
for循环的例子:
答案:
解决方法上面有说到: 在调用remove方法之后执行 i--;
成功解决: