Java OCA OCP Practice Question 2330

Question

Which declaration can be inserted at (1) so that the program compiles and runs without errors?

public class Main {
 public static void main(String[] args) {
   //  (1) INSERT DECLARATION HERE
   for (int i = 0; i <= 5; i++) {
     List<Integer> row = new ArrayList<Integer>();
     for (int j = 0; j <= i; j++)
       row.add(i * j);//from  w  w w. j  a  v a 2 s .  co m
     ds.add(row);
   }
   for (List<Integer> row : ds)
      System.out.println(row);
 }
}

Select the one correct answer.

  • (a) List<List<Integer>> ds = new List<List<Integer>>();
  • (b) List<ArrayList<Integer>> ds = new ArrayList<ArrayList<Integer>>();
  • (c) List<List<Integer>> ds = new ArrayList<List<Integer>>();
  • (d) ArrayList<ArrayList<Integer>> ds = new ArrayList<ArrayList<Integer>>();
  • (e) List<List<Integer>> ds = new ArrayList<ArrayList<Integer>>();
  • (f) List<List, Integer> ds = new List<List, Integer>();
  • (g) List<List, Integer> ds = new ArrayList<List, Integer>();
  • (h) List<List, Integer> ds = new ArrayList<ArrayList, Integer>();


(c)

Note

(a) Cannot instantiate the interface List.

(b) and (d) The method call ds.

add(row) expects a list with element type ArrayList<Integer>, but row has the type List<Integer>.

(e) Incompatible types for assignment: cannot convert from ArrayList<ArrayList<Integer> to List<List<Integer>.

(f) The interface List requires a single type parameter, and it cannot be instantiated.

(g), (h) Both the interface List and the class ArrayList require a single type parameter.




PreviousNext

Related