ProgrammingVery hardProduct-company placement · Java

Which lines fail to compile?

Which lines fail to compile?
List<? super Integer> l = new ArrayList<Number>();
l.add(1);              // L1
l.add(2.5);            // L2
Object o = l.get(0);   // L3
Integer i = l.get(0);  // L4
  1. A. L4 only
  2. B. L2 and L4
  3. C. L1 and L2
  4. D. L2, L3 and L4

Correct answer: B. L2 and L4

? super Integer accepts Integer (and subtypes) as input, so L1 compiles but a Double (L2) does not. Reading gives only Object, so L3 is fine and L4 needs a cast. (PECS: producer extends, consumer super.)

More OOP with C++ and Java questions

Exams that ask this topic