通配符和'T'之间有什么区别? [英] What's the difference between wildcard and 'T'?
问题描述
public <? extends Animal> void takeThing(ArrayList<?> list)
public <T extends Animal> void takeThing(ArrayList<T> list)
为什么这个陈述错了?我的意思是为什么?
不能在前面使用?但是 T
可以。有什么区别?
Why this statement is wrong? I mean why the ?
can't be used in the front? But T
can. What is the difference?
以下是这个问题的答案。但我不明白这是什么意思。
如果你说void,则没有返回类型。如果你指定那么有一个返回类型。我不知道你可以指定有返回类型或没有返回类型。
Here is an answer for this question.But I don't get what this mean. "if you say void then there is no return type. if you specify then there is a return type. i didn't know that you can specify to have return type or no return type."
推荐答案
public void takeThing(ArrayList<? extends Animal> list)
表示对任何 动物$ c $的子类列表执行某些操作c>。
public <T extends Animal> void takeThing(ArrayList<T> list)
表示使用某些列表执行某些操作 Animal
的特定子类(AKA T
)。
如果我在第一个方法上调用 list.get()
,我所知道的返回类型是它扩展 Animal
。在第二种方法,如果我有另一个 List< T>
的实例,我知道无论 T
类型是什么,两个列表都会接受相同的类型。
If I call list.get()
on the first method, all I know about the returned type is that it extends Animal
. On the second method, if I had another instance of List<T>
, I know that whatever type T
is, both lists would accept the same type.
如果我说的话,那就更进一步了。
To take it even further, if I say
Animal animal = list.get(0);
我不能再说了
list.add(animal);
即使在同一个列表中也是如此,因为我们没有对泛型子类型的引用。但是,如果我宣布列表< T>
其中< T extends Animal>
,我现在可以说
even on the very same list, because we don't have a reference to the generic subtype. If however, I declare a List<T>
where <T extends Animal>
, I can now say
T animal = list.get(0);
list.add(animal);
因为我们知道 list
需要元素输入 T
。
because we know that list
expects elements of type T
.
这篇关于通配符和'T'之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!