0

Possible Duplicate:
what is the difference between 'super' and 'extends' in Java Generics
Java Generics WildCard Question: List<? extends A>

I discovered a strange behaviour of Java generics that I can't explain to myself.

If I try the following code, I would expect that it should work

List<? extends Number> list = new ArrayList<>();
list.add(new Integer(2));
list.add(new Float(2.0f));

But this leads to an compiler error.

If I change the first line to

List<? super Number> list = new ArrayList<>();

it works fine for the compiler.

Can anyone explain that to me? What is the difference between ? extends and ? super ?

Community
  • 1
  • 1
Tobias Breßler
  • 316
  • 3
  • 8
  • http://docs.oracle.com/javase/tutorial/java/generics/wildcards.html – Keppil Oct 09 '12 at 06:59
  • also see http://stackoverflow.com/questions/12082780/adding-an-element-inside-a-wildcard-type-arraylist – Jesper Oct 09 '12 at 07:00
  • also see http://stackoverflow.com/questions/2776975/how-can-i-add-to-list-extends-number-data-structures – Jesper Oct 09 '12 at 07:01
  • also see http://stackoverflow.com/questions/1910892/what-is-the-difference-between-super-and-extends-in-java-generics and the links in that question. – Jesper Oct 09 '12 at 07:03

1 Answers1

1

See Effective Java 2nd Edition, Item 28:

Producer extends, Consumer super

If your parameter is a producer, it should be <? extends T>, if it's a consumer it has to be <? super T>

Here it is consumer so it must be <? super Number>

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103