java Java泛型通配符:<? 扩展数> vs <T扩展数>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11497020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Generics WildCard: <? extends Number> vs <T extends Number>
提问by vikky.rk
What is the difference between these 2 functions?
这两个函数有什么区别?
static void gPrint(List<? extends Number> l) {
for (Number n : l) {
System.out.println(n);
}
}
static <T extends Number> void gPrintA(List<T> l) {
for (Number n : l) {
System.out.println(n);
}
}
I see the same output.
我看到相同的输出。
采纳答案by Thilo
There is no difference in this case, because T
is never used again.
在这种情况下没有区别,因为T
不再使用。
The reason for declaring a T
is so that you can refer to it again, thus binding two parameter types, or a return type together.
声明 a 的原因T
是为了您可以再次引用它,从而将两个参数类型或一个返回类型绑定在一起。
回答by Bohemian
The difference is you can't refer to T
when using a wildcard.
不同之处在于您T
在使用通配符时不能引用。
You aren't right now, so there is "no difference", but here's how you could use T
to make a difference:
您现在不在,因此“没有区别”,但您可以使用以下方法T
来有所作为:
static <T extends Number> T getElement(List<T> l) {
for (T t : l) {
if (some condition)
return t;
}
return null;
}
This will return the same typeas whatever is passed in. eg these will both compile:
这将返回与传入的任何类型相同的类型。例如,它们都将编译:
Integer x = getElement(integerList);
Float y = getElement(floatList);
回答by ns89
T
is a bounded type, i.e. whatever type you use, you have to stick to that particular type which extends Number
, e.g. if you pass a Double
type to a list, you cannot pass it a Short
type as T
is of type Double
and the list is already bounded by that type. In contrast, if you use ?
(wildcard
), you can use "any" type that extends Number
(add both Short
and Double
to that list).
T
是有界类型,即无论您使用什么类型,您都必须坚持扩展的特定类型Number
,例如,如果您将Double
类型传递给列表,则不能将Short
类型按原样传递给它T
,Double
并且列表已经受该类型限制类型。相反,如果使用?
( wildcard
),则可以使用扩展的“任何”类型Number
(将Short
和都添加Double
到该列表中)。
回答by Kanagaraj M
When you use T you can perform all type of actions on List. But when you use you can not perform add.
当您使用 T 时,您可以对 List 执行所有类型的操作。但是当你使用时你不能执行添加。
T - as same as object reference with full access
? - give partial access
T - 与具有完全访问权限的对象引用相同
?- 提供部分访问权限
static void gPrint(List<? extends Number> l) {
l.add(1); //Will give error
for (Number n : l) {
System.out.println(n);
}
static <T extends Number> void gPrintA(List<T> l) {
l.add((T)1); //We can add
for (Number n : l) {
System.out.println(n);
}