我有以下代码因为一般性问题而无法编译。它来自我尝试运行代码时。问题是我必须解决一般问题,但我无法发现它是否必须在StAlgo类或方法中改变某些东西。
public class StAlgo{
//signature selection sort
public <T extends Comparable<T>> int selectionSort(T[] array) {
}
public static <T extends Comparable<T>> T[] getRandomPermutationOfIntegers(int size) {
T[] data = (T[])new Comparable[size];
for (Integer i = 0; i < size; i++) {
data[i] = (T)i;
}
// shuffle the array
for (int i = 0; i < size; i++) {
T temp;
int swap = i + (int) ((size - i) * Math.random());
temp = data[i];
data[i] = data[swap];
data[swap] = temp;
}
return data;
}
public <T extends Comparable<T>> void trySelectionSort(){
int N = 100, M = 100;
for(int i= 0; i < N; i++){
T[] arrayInts = (T[])new Comparable[i];
for(int j= 0; j < M; i++){
arrayInts = getRandomPermutationOfIntegers(i);
//Collections.shuffle(Arrays.asList(arrayInts));
selectionSort(arrayInts);
}
}
}
}
//Main class has the folling code:
StAlgosa s = new StAlgosa();
s.trySelectionSort();
我收到以下错误:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Bound mismatch: The generic method trySelectionSort() of type StAlgosa is not applicable for the arguments (). The inferred type Comparable<Comparable<T>> is not a valid substitute for the bounded parameter <T extends Comparable<T>>
我该如何解决?
感谢
答案 0 :(得分:1)
部分修复方法是:
public class StAlgo<T extends Comparable<T>>
但是,您仍然会遇到问题
data[i] = (T) i;
因为您在该循环中创建了整数,但您的T类型可能无法隐式赋值...
答案 1 :(得分:0)
这看起来像类型擦除问题 - http://download.oracle.com/javase/tutorial/java/generics/erasure.html
当你做T扩展Foo&lt; T&gt;,编译后,Java只记得T extends Foo。
结帐Generic Restriction Hell: Bound Mismatch帖子了解更多信息。