我有一个 Java 方法,它接受一个通用数组作为输入:
void insertionSort(T[] data) {
T sortValuePointer;
for (int i = 1; i < data.length; i++) {
sortValuePointer = data[i];
int j = i;
while (j > 0 && compare(sortValuePointer,data[j - 1]) < 0) {
data[j] = data[j - 1];
j--;
}
data[j] = sortValuePointer;
}
}
我有一个创建如下的数组:
T[] temp= (T[]) Array.newInstance(t, 5);
其中类 t 作为输入:
Class<T> t;
并且方法insertionSort位于InsertionSort类中。所以我无法调用如下电话:
insertionSort.insertionSort(temp);
我收到以下编译时错误: 线程“main”java.lang.Error 中出现异常: Unresolved 编译问题:
The method insertionSort(Integer[]) in the type InsertionSort<Integer> is not applicable for the arguments (T[])
最佳答案
我解决了这个问题。问题是我正在使用特定类型创建父类!就我而言,这是:
InsertionSort<Integer> insertionSort = new InsertionSort<Integer>();
本来应该是:
InsertionSort<T> insertionSort = new InsertionSort<T>();
这解决了问题。
关于java - 将泛型数组传递给采用泛型数组的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33532420/