我想在 try-catch 中清除一个 ArrayList。我知道我们可以用方法来做到这一点。但是clear()
当我尝试用 for 循环清除每个项目时。它显示以下结果:
public class ArrayListTryCatch {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList();
int oldsize = list.size();
try {
list.add(20);
list.add(30);
list.add(40);
int wrongDivide = 1 / 0;
} catch (Exception e) {
for (int i = 0; i < list.size(); i++) {
System.out.println("deleted item: " + list.get(oldsize));
list.remove(i);
}
}
System.out.println(list.size());
System.out.println("after try catch: ");
for (Integer e : list) {
System.out.println(e);
}
}
}
结果是:
deleted item: 20
deleted item: 30
1
after try catch:
30
我认为它必须是空的 ArrayList。我有什么麻烦?