问题描述
所以我继续在下一个代码中遇到错误.而且我不知道我在做什么错.错误为:main类型中的方法printArray(T [])不适用于参数(int [])
So i keep on getting an error on the next code. And I have no idea what i'm doing wrong.The error is The method printArray(T[]) in the type main is not applicable for the arguments (int[])
public class main {
public static void main(String[] args) {
Oefening1 oef = new Oefening1();
int[] integerArray = {1,2,3,4,5};
printArray(integerArray);
}
public static <T> void printArray(T[] arr){
for(T t: arr){
System.out.print(t + " ");
}
System.out.println("");
}
}
推荐答案
在泛型方面,Java在原始类型和从 java.lang.Object
派生的类型之间有所区别.只有非原始类型可以用作泛型方法的参数.由于 int
不是通用的,因此 printArray< T>
不适用于它.
When it comes to generics, Java makes a difference between primitive types and types derived from java.lang.Object
. Only non-primitive types can be used as arguments of generic methods. Since int
is not generic, printArray<T>
does not apply to it.
您可以通过提供 int
的重载或将 integerArray
设置为 Integer []
来解决此问题:
You can fix it by providing an overload for int
, or by making integerArray
an Integer[]
:
Integer[] integerArray = {1,2,3,4,5};
printArray(integerArray);
之所以可行,是因为 Integer
将 int
包装在适合传递给泛型的对象中.但是,这需要Java编译器的大量帮助,因为编写 {1,2,3,4,5}
时,它会转换为 {Integer.valueOf(1),Integer.valueOf(2),Integer.valueOf(3),Integer.valueOf(4),Integer.valueOf(5)}
在幕后.
The reason this works is that Integer
wraps int
in an object suitable for passing to generics. However, this takes a lot of help from Java compiler, because when you write {1,2,3,4,5}
it gets translated to {Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5)}
behind the scene.
这篇关于Java泛型:无法创建简单的打印数组方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!