I get the point that “? extends E” means is that it is ok to add all members of a collection with elements of any type that is a subtype of E. Hence for a List , addAll(all values of List) will hold good. But then why it is generalised that "Use an extends wildcard when you only get values out of a structure" as per The Get and Put Principle ?
Asked
Active
Viewed 880 times
1
-
1It has already been discussed thousands of times, e.g. here: http://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super – Ivan Pronin Apr 06 '17 at 13:42
-
*“? extends E” means is that it is ok to add all members of a collection with elements of any type that is a subtype of E.* No, it doesn’t. It means it accepts elements of a specific subtype which may be E or may be a descendant of E. You cannot add Integers or Doubles to a `Collection extends Number>`, because it *might* be a `Collection
` or it *might* be a `Collection – VGR Apr 06 '17 at 14:11` or it might be a `Collection `, etc.
1 Answers
1
When you addAll
from the parameter Collection
, you're "getting" all the elements in the Collection
parameter and adding them to another collection. Therefore "Producer Extends (Consumer Super)" still applies here.
By enforcing the generic <? extends E>
, we are ensuring that all elements in the parameter are instanceof E
, and can therefore be successfully added to a Collection<E>
.

Zircon
- 4,677
- 15
- 32
-
See also example source code for [`addAll`](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/AbstractCollection.java#AbstractCollection.addAll%28java.util.Collection%29) which could also elucidate the point. – Radiodef Apr 06 '17 at 13:44