问题
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("");
}
}
回答1:
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.
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);
Demo.
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.
回答2:
Its because you are using primitive type of the data type. If you use Integer[] integerArray = {1,2,3,4,5}; instead of int[] integerArray = {1,2,3,4,5};. It should work.
来源:https://stackoverflow.com/questions/27706282/java-generics-cant-create-a-simple-print-array-method