通用方法< T>在Java中 [英] generic method <T> in Java
问题描述
下一个方法是通用的,但我只想知道< T>
?的有用性,我的意思是< T> ;
谁在静态之前,之前将无效。如果我不写我的方法,会发生什么?
public static< T> void nameMethod(BinaryTreeNode< T> t){
/ *做一些
。
。
* /
}
谢谢。 b
< T>
为方法的整个上下文定义了一个类型参数。据我所知,在这个特殊情况下,它确实相当于
public static void nameMethod(BinaryTreeNode< ;? > t){
但是,如果您要返回类型 T
,或者如果具有多个具有相同泛型类型的参数,则需要声明类型参数,以便编译器具有用于标识类型的参考点。例如:
public static< T>列表与LT; T> mergeSort(List< T> l1,List< T> l2){
// ...
}
< T>
参数告诉编译器: List
以及返回的 List
必须是相同的泛型类型。
当我们可以声明时这更加有用有关 T
的其他信息:
public static< T extends Number>列表与LT; T> asList(T ... numbers){
//使用特定于数字的逻辑构建列表...
}
编辑:我对我的第一点不正确。即使没有附加参数或返回类型,在声明< T>
时也可能有用。因为我不熟悉这个 BinaryTreeNode
。
public static< T> void duplicateFirstElement(List< T> 1){
T elm = l.get(0);
l.add(elm);
$ / code>
如果我们要移除类型参数并将参数声明为 List<?>
,那么在与列表交互时将无法保留泛型。
The next method is generic,but I just wanna know what is the Usefulness of <T>
?, I mean the <T>
who is next to static and before to void. What happen if I don't write it in my method?.
public static <T> void nameMethod(BinaryTreeNode<T> t){
/*do something
.
.
*/
}
Thank you.
<T>
defines a type parameter for the whole context of the method. As far as I can tell, in this particular case, it would indeed be equivalent to
public static void nameMethod(BinaryTreeNode<?> t) {
However, if you're returning a type T
, or if you have more than one parameter with the same generic type, you need to declare the type parameter so the compiler has a reference point to identify the type. For example:
public static <T> List<T> mergeSort(List<T> l1, List<T> l2) {
//...
}
The <T>
parameter tells the compiler that both List
s being passed as well as the List
returned must be of the same generic type.
This is even more useful when we can declare additional information about T
:
public static <T extends Number> List<T> asList(T... numbers) {
//build list with Number-specific logic...
}
EDIT: I was incorrect about my first point. Even without additional parameters or a return type, there may be a use in declaring <T>
. I'll provide a simple example using a List
, since I'm not familiar with this BinaryTreeNode
.
public static <T> void duplicateFirstElement(List<T> l) {
T elm = l.get(0);
l.add(elm);
}
If we were to remove the type parameter and declare the parameter as List<?>
, there would be no way to retain the generic type while interacting with the list.
这篇关于通用方法< T>在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!