问题
Declaration like this :
class A<X extends Number & List> { }
is allowed.Whereas declaration like this is not allowed.
class A<? extends Number & List> { }
Is there any logical explanation about why Java restricts us to do that?
& what's the actual difference between
<T extends Number>
& <? extends Number>?
回答1:
The whole point of a type parameter like T
is so that you can use it as a type inside the class. What would a wildcard there even mean? If you can't use it anywhere, why have a type parameter at all?
回答2:
If you used <? extends Number & List>
, then you wouldn't be able to do anything with the type parameter. It'd be completely useless.
Similarly, ? extends Number
lets you deal with the special case when you don't need to refer to the type that extends number, and you don't need to give it a name.
回答3:
Generic class and interface declarations want type parameters, such as T or U. ? is a wildcard, better used for method parameters that are themselves generic:
class Foo<T extends Number & List> {
void doStuff(List<T> items) {
// ...
}
void doMoreStuff(List<? extends OutputStream> streams) {
// ...
}
}
doStuff() indicates that it wants to operate on a List<T>
where T is the type parameter on class Foo. So:
class Weird extends Number implements List {
//
}
Foo<Weird> f = new Foo<Weird>();
f.doStuff(...); // wants a List<Weird>
If we called doMoreStuff() on f, we could hand it something of type List<OutputStream>
, List<FilterOutputStream>
, List<ByteArrayOutputStream>
, etc.
来源:https://stackoverflow.com/questions/9914302/why-wild-cards-cant-be-used-in-generic-class-method-declaration