0
List<? super Integer> integers = new ArrayList<Number>();
List<? extends Number> integers2 = new ArrayList<Number>();
integers.add( new Integer(4));
integers2.add(new Integer(4));

I'm getting compiler error at last line, may i know why ? even though Integer does extends Number im getting the following error

The method add(capture#3-of ? extends Number) in the type List<capture#3-of ? extends 
 Number> is not applicable for the arguments (Integer)
amarnath harish
  • 791
  • 6
  • 18
  • also interesting https://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-are-java-generics-not-implicitly-po – Tim Jun 29 '18 at 12:49

1 Answers1

3

Because List<? extends Number> is not a List<Number>.

List<? extends Number> could be, for example, a List<Double> or a List<Float>:

List<? extends Number> integers2 = new ArrayList<Double>(); //valid

It would not be valid to add an integer to a list of doubles, which is why the compiler prevents you from doing this.

You should probably not be using a wildcard (?) in this situation.

Michael
  • 34,340
  • 9
  • 58
  • 100
  • 1
    i totally get it , but why its throwing the error in compile time, it can also be an INTEGER right – amarnath harish Jun 29 '18 at 12:49
  • 1
    this question has been asked and answered many times already. The usual course of action here is to close as duplicate rather than increase fragmentation of information – Tim Jun 29 '18 at 12:51
  • 1
    @TimCastelijns True enough. I don't know why I went straight into auto-answer mode. Because I have gold badge dupe close privileges, I've made this a community wiki so I don't get rep unfairly from the question no longer being open for new answers – Michael Jun 29 '18 at 12:57
  • 2
    @amarnathharish Java is all about pushing problem detection to compile time. Generics are a safe feature that was introduced to move related bug detection to compile time. Java does not wait for the actual type to show up at runtime, it detects that this **might** lead to an error and throws a compile time error. If you want a `List` that accepts all numbers, then write `List`. It is important to note that `? extends Number` does **not mean** *everything that extends is valid and can be mixed*. It is still locked to one single explicit type, defined by the caller. – Zabuzard Jun 30 '18 at 10:11