import java.util.*;
public class AddingIntegers{
public static void main(String []args){
ArrayList <Integer> list = new ArrayList<>(Arrays.asList(10,20,30));
add(list);
}
public static void add(ArrayList<Integer> list) {
for (int i = list.size() - 1; i >= 0; i--) {
if (i % 2 == 0) {
list.add(list.get(i));
} else {
list.add(0, list.get(i));
}
}
System.out.println(list);
}
}
Expected output: [20, 10, 20, 30, 30, 10]
Actual output: [20, 10, 20, 30, 30, 20]
So I don't understand why, for the last index, when i = 0, 20 is added at the end of the list, which should be 10 as far as I'm concerned.
Let's see what happens with each loop. Start: [10, 20, 30]
.
i = 2
The expression
i % 2
is0
, so the element at index 2 (30
) is appended to the end of the list. The list is now[10, 20, 30, 30]
.i = 1
The expression
i % 2
is1
, so the element at index 1 (20
) is inserted at the beginning of the list. The list is now[20, 10, 20, 30, 30]
. Note that20
is now at the beginning of the list.i = 0
The expression
i % 2
is0
, so the element at index 0 (20
) is appended to the end of the list. The list is now[20, 10, 20, 30, 30, 20]
. Note that20
is appended, not10
, because10
is no longer at the beginning of the list,20
is.