LearnFrenzy
Sign in Take a free test

Generics · Find the Error · Question 8

Error: reading an Integer from List<? super Integer> Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links