Java 找不到符号 - 类 T
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18787932/
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
Cannot find symbol - class T
提问by Nir
I've this function;
我有这个功能;
public static T[] addToArray(T item, T... items){
T[] array;
int array_size = 1;
if(items !=null){ array_size = items.length+1; }
array = java.util.Arrays.copyOf(items, array_size);
array[array_size-1] = item;
return array;
}
And I get this error cannot find symbol symbol: class T
. The idea is to make this method generic. I never worked with generics so I'm guessing I miss some reference?
我收到这个错误cannot find symbol symbol: class T
。这个想法是使这个方法通用。我从来没有使用过泛型,所以我猜我错过了一些参考?
采纳答案by Siva
Method signature for generic method is as follows
泛型方法的方法签名如下
public static <T> T[] addToArray(T item, T... items){
T[] array;
int array_size = 1;
if(items !=null){ array_size = items.length+1; }
array = java.util.Arrays.copyOf(items, array_size);
array[array_size-1] = item;
return array;
}
回答by Rohit Jain
You need to declare the type parameter before the return type of the method:
您需要在方法的返回类型之前声明类型参数:
public static <T> T[] addToArray(T item, T... items)
Reference:
参考:
回答by SLaks
To make a generic method, you need to declare it as taking a generic type parameter:
要创建泛型方法,您需要将其声明为采用泛型类型参数:
public static <T> T[] addToArray(...)