ProgrammingHardAmazon/Microsoft SDE MCQ · Java placement

Which lines fail to compile?

Which lines fail to compile?
List<Integer> ints = new ArrayList<>();
List<Number> a = ints;                       // line 1
List<? extends Number> b = ints;             // line 2
b.add(Integer.valueOf(3));                   // line 3
Number n = b.isEmpty() ? null : b.get(0);    // line 4
List<? super Integer> c = new ArrayList<Number>();
c.add(4);                                     // line 5
  1. A. Lines 1 and 3 only
  2. B. Lines 1, 3 and 5
  3. C. Line 3 only
  4. D. Lines 1 and 5 only

Correct answer: A. Lines 1 and 3 only

Generics are invariant, so List<Integer> is not a List<Number> (line 1). A List<? extends Number> can be read as Number but nothing except null can be added (line 3). ? super Integer accepts Integer additions (line 5 is fine).

More OOP with C++ and Java questions

Exams that ask this topic