【问题标题】:How do i solve this generic bug我如何解决这个通用错误
【发布时间】:2011-11-01 19:53:46
【问题描述】:

由于一般问题,我的以下代码无法编译。它来自当我尝试运行代码时。问题是我必须解决通用问题,但我无法发现是否必须更改 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>>

我该如何解决?

谢谢

【问题讨论】:

  • 提供堆栈跟踪会很有用。
  • 不,不是。 “未解决的编译问题”异常意味着这个类只是没有编译,但他告诉 Eclipse 无论如何都要运行该程序。行号没有意义。

标签: java


【解决方案1】:

部分解决方法是:

public class StAlgo<T extends Comparable<T>>

但是,您仍然会遇到问题

data[i] = (T) i;

因为您在该循环中创建整数,但您的 T 类型可能无法隐式分配...

【讨论】:

    【解决方案2】:

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

    当你做 T extends Foo 时,编译后,Java 只记得 T extends Foo。

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

    【讨论】:

    • 感谢您的回复。我无法编译它来打印堆栈跟踪
    • 哦。我以为你遇到了例外。它的编译过程是什么?我的错。您能否提供编译器失败的行?这将有助于解决确切的问题
    • 这一行:s.trySelectionSort();
    • 当我使用此代码时,我收到 2 个错误 - 您将类命名错误,即 StAlgosa 并且您正在尝试分配 data[i] = (T) i。这2个是唯一的问题。在你提到的地方,我实际上没有收到错误。
    • 我明白了。班级名称对我来说不是问题。我在复制到文本编辑器时犯了错误。我的班级名称完好无损。我如何修复 data[i] = (T) i; ?
    猜你喜欢
    • 2016-07-21
    • 2016-09-09
    • 2016-07-29
    • 2015-02-28
    • 2013-08-16
    • 2020-04-17
    相关资源
    最近更新 更多