Adding integers to an ArrayList depending on the modulus of their indexes

Felicity-MB :
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.

rgettman :

Let's see what happens with each loop. Start: [10, 20, 30].

  • i = 2

    The expression i % 2 is 0, 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 is 1, 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 that 20 is now at the beginning of the list.

  • i = 0

    The expression i % 2 is 0, 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 that 20 is appended, not 10, because 10 is no longer at the beginning of the list, 20 is.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=117678&siteId=1