Java OCA OCP Practice Question 2976

Question

Given:

3. import java.util.*;  
4. public class Main {  
5.   public static void main(String[] args) {  
6.     List<Integer> x = new ArrayList<Integer>();  
7.     Integer[] a = {3, 1, 4, 1};  
8.     x = Arrays.asList(a);  // ww  w . ja  va  2s  .  co m
9.     a[3] = 2;  
10.     x.set(0, 7);  
11.     for(Integer i: x) System.out.print(i + " ");  
12.     x.add(9);  
13.     System.out.println(x);  
14. } } 

What is the result?

  • A. Compilation fails.
  • B. 3 1 4 2 [7, 1, 4, 1]
  • C. 3 1 4 2 [7, 1, 4, 2]
  • D. 7 1 4 2 [7, 1, 4, 2]
  • E. 3 1 4 2 [7, 1, 4, 1, 9]
  • F. 3 1 4 2 [7, 1, 4, 2, 9]
  • G. 7 1 4 2, followed by an exception.
  • H. 3 1 4 2, followed by an exception.


G is correct.

Note

The asList() method "backs" the List to the array.

In other words, changes to one are mirrored in the other.

However, neither can grow, so when add() is called an exception is thrown.




PreviousNext

Related