我正在学习Java的学校和主题是通用方法。我需要编写一个具有通用方法的应用程序,用相同的元素“填充”任何类型的数组。但它不工作...谁能帮助我:通用方法来填充数组
package pack.switchshift;
import java.lang.reflect.Array;
public class Filler {
public static void main(String [] args) {
int[] intArr = new int[10];
String[] stringArr = new String[10];
double[] doubleArr = new double[10];
genFill(intArr, 0);
genFill(stringArr, "0");
genFill(doubleArr, 0.0);
for (int element : intArr){
System.out.print(element);
}
}
private static <T> void genFill(T[] arr, T element) {
for (int i = 0; i < arr.length; i++) {
arr[i] = element;
}
}
}
我想在这多种方法,花了几个小时研究,但我仍然没有得到它。
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The methodgenFill(T[], T)
in the typeFiller
is not applicable for the arguments(int[], int)
The methodgenFill(T[], T)
in the typeFiller
is not applicable for the arguments(double[], double)
at pack.switchshift.Filler.main(Filler.java:11)
对于原始类型,您必须使用它们的盒装版本。 –
在这种情况下'T'没有用;你的方法签名应该是'private static void genFill(Object [] arr,Object element)' – newacct