Arraylist.remove removes first occurrence instead of index, even though I input an int in .remove(int i)
?
Let’s I have a arraylist “numbers” of random amount of numbers, for this example lets say we have {1,3,5,2,4,6}
ArrayList<Integer> numbers = new ArrayList<Integer>();
aList.add(1);
aList.add(3);
aList.add(5);
aList.add(2);
aList.add(4);
aList.add(6);
I want to remove all odd numbers based on their indices. I have created another Arraylist containing their indices through:
int origSize = numbers.size();
for (int i = 0; i < origSize; i++) {
if (numbers.get(i) % 2 != 0) {
numbers.add(numbers.get(i));
remover.add(i);
}
For some reason, when I use the .remove function to remove an element based on its index, it removes the first occurrence. My syntax is right or, I am doing .remove(int i) :
for (int i = (remover.size() - 1); i>=0; i--) {
numbers.remove(remover.get(i));
}
In my example, 5 occurs at index 2. But running .remove(remover.get(i))
, which should be .remove(2)
removes the first occurrence of 2…
Ultimately, I get {3,5,4,6} because it removes the 2,1 and 0 instead of those indices. Why is this happening?
Thanks so much for your help.