128k views
1 vote
Consider the following code segment.

ArrayList vals = new ArrayList();
vals.add(vals.size(), vals.size());
vals.add(vals.size() - 1, vals.size() + 1);
vals.add(vals.size() - 2, vals.size() + 2);
System.out.println(vals.toString());
What is printed as a result of executing the code segment?

User Hos Ap
by
7.7k points

1 Answer

1 vote

Final answer:

The code results in the ArrayList containing the elements [4, 2, 0], since elements are added at varying indexes based on the ArrayList's current size. The final output printed is '[4, 2, 0]'.

Step-by-step explanation:

The question relates to Java programming and specifically the use of the ArrayList class. When the code runs, it performs the following operations:

  1. Adds an element at the end of the list. Since the list is empty, vals.size() is 0. The element 0 is added at index 0 (vals.add(0, 0)).
  2. Adds an element before the last element in the list. Now, vals.size() is 1, so it adds the element 2 at index 0 (vals.add(0, 2)).
  3. Adds an element two positions before the last element. At this point, vals.size() is 2, so it adds the element 4 at index 0 (vals.add(0, 4)).

Therefore, the contents of the ArrayList after the execution of this code are [4, 2, 0]. When vals.toString() is called, it prints the ArrayList elements as a single string. Hence, the output of this code segment is [4, 2, 0].

User Rafael Carvalho
by
9.1k points