This was closed as being a duplicate of the PECS question. PECS is just a mnemonic that does more harm than good because people just memorize it without really understanding the deeper issues. Please reopen.
Update:
What I understood from @rzswitzerloot's explanation below is: the wildcard just refers to the type of element in the Array. It does not mean one can add the wildcard type to the array - in fact, one can only add descendants of the type (including itself, in this case, 'B').
I am confused by whether wildcards <? super Number>
refers to a superclass like Object
or a subtype like Integer
. In "Java OCP 17 Developer Complete Study Guide" by Jeanne Boyarsky and Scott Selikoff, (Chapter 9 Collections and Generics)
Generics allow you to specify wildcards. <?> is an unbounded wildcard that means any type. <? extends Object> is an upper bound that means any type that is Object or extends it. <? extends MyInterface> means any type that implements MyInterface. <? super Number> is a lower bound that means any type that is Number or a super class. A compiler error results from code that attempts to add an item in a list with an unbounded or upper-bounded wildcard
A super class as I understand, is a parent of Number. But then, why cannot one do this?
import java.util.ArrayList;
import java.util.List;
public class Bewildered {
static class A {}
static class B extends A {}
static class C extends B {}
public static void main(String[] args) {
List<? super B> listBs = new ArrayList<>();
listBs.add(new A());
}
}
compile error:
java: incompatible types: Bewildered.A cannot be converted to capture#1 of ? super Bewildered.B