LearnFrenzy
Sign in Take a free test

Generics · Find the Error · Question 2

Error: adding to a List<? extends Number> Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 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 void addBonus(List<? extends Number> scores) {
        scores.add(10);
    }

    public static void main(String[] args) {
        addBonus(new ArrayList<Integer>());
    }
}
  • A 10 must be 10.0
  • B The list could be a List<Double>, so nothing (except null) can be added through ? extends Number; use List<? super Integer> to add Integers Correct
  • C ArrayList cannot be passed
  • D add needs an index
Correct Answer: Option B

Producer extends – it is for reading only.

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