2011-11-01 54 views
0

我有下面的代码,因为一般的问题,将不会编译。它来自当我尝试运行代码。问题是我必须解决一般问题,但我无法发现它是否必须更改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>> 

如何解决呢?

感谢

+1

这将是给出来的堆栈跟踪有用。 – Pavan

+0

不,不是真的。 “未解决的编译问题”异常意味着这个类没有编译,但他告诉Eclipse无论如何都要运行该程序。行号不会有意义。 –

回答

0

这看起来像类型擦除一个问题 - http://download.oracle.com/javase/tutorial/java/generics/erasure.html

当你做T延伸美孚<牛逼>,编译后,Java的只是回忆牛逼延伸富。

结帐Generic Restriction Hell: Bound Mismatch后以获取更多信息。

+0

我的意思是牛逼延伸富。格式化吃了我的“”。 – Pavan

+0

感谢您的回复。我无法编译它来打印栈跟踪 –

+0

哦。我以为你得到了一个例外。它的编译过程就是这样吗?我的错。你可以,然后提供编译器失败的行吗?这将有助于修复这一行的确切问题 – Pavan

1

部分修复是有这样的:

public class StAlgo<T extends Comparable<T>> 

但是,你仍然会在

data[i] = (T) i; 

有问题,因为你在一个循环使得整数,但你的T型可能不隐式分配...