[英]Why Wild Cards can't be used in generic class & method declaration?
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? 关于Java为什么限制我们这样做的逻辑解释?
& what's the actual difference between 和之间的实际区别是什么
<T extends Number>
& <? extends Number>?
If you used <? extends Number & List>
如果您使用
<? extends Number & List>
<? extends Number & List>
, then you wouldn't be able to do anything with the type parameter. <? extends Number & List>
,那么您将无法使用type参数执行任何操作。 It'd be completely useless. 这将完全没有用。
Similarly, ? extends Number
同样,
? extends Number
? 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. 当您不需要引用扩展数字的类型并且不需要给它起名字时,
? extends Number
可以让您处理特殊情况。
The whole point of a type parameter like T
is so that you can use it as a type inside the class. 像
T
这样的类型参数的要点是,因此您可以将其用作类中的类型。 What would a wildcard there even mean? 那里的通配符甚至意味着什么? If you can't use it anywhere, why have a type parameter at all?
如果您无法在任何地方使用它,为什么还要有一个type参数呢?
Generic class and interface declarations want type parameters, such as T or U. ? 通用类和接口声明需要类型参数,例如T或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. doStuff()表示要对
List<T>
进行操作,其中T是类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. 如果在f上调用doMoreStuff(),我们可以将其交给
List<OutputStream>
, List<FilterOutputStream>
, List<ByteArrayOutputStream>
等类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.