问题
Code:
List<? extends Integer> ints= new ArrayList<Integer>();
ints.add(3);//error
I still dont understand how it works. Question:
What does mean CAP#1
? Is it a reference type? I think, no, because CAP#1 doesnt inherited from Object
. We can write ints.add(null);//OK
and we havent compile time error. But we cant write null instanceof CAP#1;//compile-time error
. Why we cant instanciate CAP#1
:
CAP#1 c= new CAP#1();
From what CAP#1
appears?
回答1:
CAP#1
is the compiler's name for the implicit type variable represented by the '?
'. There is no such named type, but the compiler needs to create a placeholder for the type in order to complete its work. The name stands for "capture".
It helps to mentally rewrite a type like G<? extends T>
to ∃CAP#1 extends T: G< CAP#1 >
.
You can't add anything to a list with a wildcard extends type, because you don't know what that wildcard stands for. Just like you can't add a Snake
to a List< Mammal >
, you can't add it to a List< ? extends Animal >
because that ?
might turn out to represent Mammal
.
You can, however, always add null
in this situation because null
is effectively a member of every reference type, which necessarily includes whatever the ?
could possibly represent.
I've often wondered why Java doesn't treat List< ? extends F >
for some final type F
the same as List< F >
. Maybe it's because F
could itself be a generic wildcard type, which would mean it would still have arbitrarily many subtypes.
Aside from Angelika Langer's famous FAQ about Java generics, I've been compiling some things about them in my own list.
回答2:
means Number or an unknown a sub class. If you obtain such a value it will be a Number, but you cannot give a value of this type because you don't know which is valid.
for more follow this answer: What is the difference between List<Number> and List<? extends Number>?
来源:https://stackoverflow.com/questions/19311808/wildcard-how-it-works