0

Not able to understand why this is disallowed.

List<? super Number> numList = Arrays.asList(1, 2, 3.0, "hello");  
List<? super Number> l = new ArrayList<>();
l.add(1);
numList.addAll(l); // <----- Error Here

The Error Description:

'addAll(java.util.Collection<? extends capture<? super java.lang.Number>>)' in 'java.util.List' cannot be applied to '(java.util.List<capture<? super java.lang.Number>>)'
David Conrad
  • 15,432
  • 2
  • 42
  • 54
Khanna111
  • 3,627
  • 1
  • 23
  • 25
  • Does this answer your question? [Java Generics PECS , add capture ? super cannot be applied to java.util.list](https://stackoverflow.com/questions/75667328/java-generics-pecs-add-capture-super-cannot-be-applied-to-java-util-list) – skomisa Jul 14 '23 at 21:58
  • [See this answer from rzwitserloot for a terrific explanation of your problem](https://stackoverflow.com/a/75667524/2985643). It is one of the best written answers I have seen on SO on any subject. – skomisa Jul 14 '23 at 22:03

1 Answers1

4

The bounded wildcard ? super Number represents some type that is a supertype of Number. However, it's unknown what specific type that is, so two different wildcards of the same bounds could refer to different types.

For instance, numList could be a List<Number> and l could be a List<Object> (both of which are valid because Object and Number satisfy the wildcard). In this case, it is clear that you cannot add arbitrary Objects to a List of Numbers.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80