Question 8
Back to Exercise
The program below does not compile. Which statement correctly describes the problem?
import java.util.ArrayList;
import java.util.List;
public class Main {
static int first(List<? super Integer> list) {
Integer x = list.get(0);
return x;
}
public static void main(String[] args) {
List<Number> nums = new ArrayList<>(List.of(1, 2));
System.out.println(first(nums));
}
}
- A get needs an Integer index
- B The list may be a List<Object> or List<Number>, so get returns Object, which cannot be assigned to Integer; use List<? extends Integer> or List<Integer> for reading Correct
- C first must be generic
- D nums must be List<Integer>
Correct Answer: Option B
Consumer super – it is for writing.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!