[英]Java: generic type array as function parameter
I have some Java 8 code like the following snippet. 我有一些Java 8代码,例如以下代码段。
public class Test {
static protected <T extends Comparable<T>> T[] myFunction(T[] arr) {
// do stuff...
return arr;
}
public static void main(String[] args) {
int[] a = new int[] {1,4,25,2,5,16};
System.out.println(Arrays.toString(myFunction(a)));
}
}
When I try to run it, I get the error below: 当我尝试运行它时,出现以下错误:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
线程“主”中的异常java.lang.Error:未解决的编译问题:
The method myFunction(T[]) in the type LottoResult is not applicable for the arguments (int[])LottoResult类型的方法myFunction(T [])不适用于参数(int [])
Why does this happen and how do I have to rewrite it to be able to also pass int[]
arrays to myFunction
? 为什么会发生这种情况,以及如何重写它才能将
int[]
数组传递给myFunction
?
An array T[]
implies that the array is of some-reference type T
, while you're passing an array of primitives ( int[]
). 数组
T[]
表示该数组是某种引用类型T
,而您正在传递原始数组( int[]
)。 This is why you get the compilation error. 这就是为什么您会收到编译错误的原因。
In order to get it working, you need to do: 为了使其正常工作,您需要执行以下操作:
Integer[] a = new Integer[] {1,4,25,2,5,16};
This will create an array of a reference type ( Integer[]
), because auto-boxing would have taken place. 这将创建引用类型的数组(
Integer[]
),因为会发生自动装箱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.