What is the result of the following code execution?

import java.util.ArrayList;
public class Test {
    public static void main(String[] args) {
        ArrayList<Integer> array = new ArrayList<Integer>(2);
        array.add(5);
        array.add(6);
        array.add(1, 7);
        System.out.print(array.indexOf(6));

        array.remove(1);
        System.out.println(array.indexOf(6));
    }
}
Explanation

ArrayList array = new ArrayList(2);
Number 2 specifies the initially allocated size of the container, i.e. memory for 2 elements will be allocated. The size() of array list is equal to zero, because it does not contain any elements yet

array.add(5);
array.add(6);
ArrayList stores its elements in order of their addition.
I.e.
element #0 = 5
element #1 = 6

Following addition form:
array.add (1,7);
means that number 7 should be inserted at the index 1, as the container is consistent and it supports the order of elements addition from left to right, then during new element addition number 6 will move to the right and will become the second element in the container
0 1 2 - elements in the container.
5 7 6 - actual numbers

array.indexOf(6)
prints out an index of the number 6 (it is equal to two in given example).
array.remove (1);
removes the element with index 1, i.e. numbers 7 and 6 return to their places

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes