Java OCA OCP Practice Question 3159

Question

Which sequence of digits will the following program print?

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<String> list = new ArrayList<String>();
    list.add("1");
    list.add("2");
    list.add(1, "3");
    List<String> list2 = new LinkedList<String>(list);
    list.addAll(list2);//from www.  j  a va  2 s . co  m
    list2 = list.subList(2, 5);
    list2.clear();
    System.out.println(list);
  }
}

Select the one correct answer.

  • (a) [1, 3, 2]
  • (b) [1, 3, 3, 2]
  • (c) [1, 3, 2, 1, 3, 2]
  • (d) [3, 1, 2]
  • (e) [3, 1, 1, 2]
  • (f) None of the above.


(a)

Note

[1, 3, 2] is printed.

First, "1" and "2" are appended to an empty list.

Next, "3" is inserted between "1" and "2", and then the list is duplicated.

The original list is concatenated with the copy.

The sequence of elements in the list is now "1", "3", "2", "1", "3", "2".

Then a sublist view allowing access to elements from index 2 to index 5 (exclusive) is created (i.e., the subsequence "2", "1", "3").

The sublist is cleared, thus removing the elements.

This is reflected in the original list and the sequence of elements is now "1", "3", "2".




PreviousNext

Related