I want to clear an ArrayList in try-catch. I do know that we can do it with clear()
method.But when I try clear every items with for loop. It show below result:
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);
}
}
}
and the result is:
deleted item: 20
deleted item: 30
1
after try catch:
30
I thinked It must be empty ArrayList. What trouble I have is?
The problem has nothing to do with try/catch, and everything to do with this loop:
for (int i = 0; i < list.size(); i++) {
System.out.println("deleted item: " + list.get(oldsize));
list.remove(i);
}
That will only remove every other element. (It will also print different items than the ones it actually deletes, which is odd...)
Suppose you start off with A, B, C, D, E.
On the first iteration, i
will be 0, the size will be 5, and you'll remove A. That will leave B, C, D, E.
On the second iteration, i
will be 1, the size will be 4, and you'll remove C (which is now at position 1). That will leave B, D, E.
On the third iteration, i
will be 2, the size will be 3, and you'll remove E (which is now at position 2). That will leave B, D.
Next, i
will be 3, the size will be 2, and the loop will terminate.
Options:
For example:
// Work from the back...
for (int i = list.size() - 1; i >= 0; i--) {
System.out.println("deleted item: " + list.get(i));
list.remove(i);
}
Or (less efficient):
while (list.size() > 0) {
System.out.println("deleted item: " + list.get(0));
list.remove(0);
}
See more on this question at Stackoverflow