要用 Iterator迭代並且用 Iterator.remove()移除(原始 list會被修改).
下面的程式碼不可行(throw ConcurrentModificationException)
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 100; i++) {
list.add(Integer.valueOf(i));
}
String point1 = "point1: ";
String point2 = "point2: ";
log.debug(point1 + list.size());
if (integer % 7 == 0) {
list.remove();
}
log.debug(point2 + list.size());
}
必須用傳統的 for(int i=0....
Integer integer = null;
for (int i = 0; i < list.size(); i++) {
log.debug(point1 + list.size());
integer = list.get(i);
if (integer % 7 == 0) {
list.remove(i);
}
log.debug(point2 + list.size());
}
或 Iterator.remove()
或 Iterator.remove()
Integer integer = null;
for (Iterator<Integer> itr = list.iterator(); itr.hasNext();) {
log.debug(point1 + list.size());
integer = itr.next();
if (integer % 7 == 0) {
itr.remove();
}
log.debug(point2 + list.size());
}