List<String> list = new ArrayList<String>;
list.add(....);
for (int i=0; i<list.size(); i++) {
if (expression) {
list.remove(i); // or list.remove(list.get(i));
}
}
[color=red]then....throw IndexOutOfBoundsException[/color]
这个问题主要是在循环中删除数组元素导致的,碰到过两次了,记录一下几种解决方法。
1.将判断条件与数组长度分离
int fooLen = list.size();
for (int i=0; i<fooLen; i++) {
if (expression) {
list.remove(i); // or list.remove(list.get(i));
fooLen--;
}
}
2.大家普遍都会想到的方法,就是把要删除的元素保存起来,然后调用list.removeALL() 方法。// 具体写法略
3.使用Iterator 数组迭代器
for (Iterator<String> i=list.iterator(); i.hasNext(); ) {
i.next();
if (expression) {
i.remove();
}
}
三种方法,第一种直接操作数组元素,效率比较高;第二种比较费资源;第三种比较简单。