简体   繁体   English

处理 Java 泛型错误

[英]Dealing with a Java generics bug

I have some generics in the following code:我在以下代码中有一些泛型:

public <T extends Comparable<T>> int insertionSort(T[] a) {
   // throw new RuntimeException("not implemented");
      final int L = a.length;
      int compares = 0;
      
      for(int i = 1; i < L; i++){
          for(int j = i; j > 0 && a[j].compareTo(a[j - 1]) < 0; j--){
              
              Comparable tmp = a[j];   // PROBLEM HERE
              a[j] = a[j - 1];
              a[j - 1] = tmp;       // PROBLEM HERE
              
              compares++;
          }
      }
      
    return compares;
  }

// PROBLEM HERE - those two lines in the code have a fault. // PROBLEM HERE - 代码中的这两行有错误。

The errors are I can't make the assignments.错误是我无法完成任务。

a[j] is a T , not a Comparable . a[j]T ,而不是Comparable

You can only put it into a variable of type T .您只能将其放入T类型的变量中。

Your problem is that Comparable is an interface, not a class.你的问题是Comparable是一个接口,而不是一个类。 you need to create an Object of a class that implements Comparable .您需要创建一个实现Comparable的类的 Object 。

If T implements Comparable , than you can declare tmp as a T and use that:如果T实现Comparable ,那么您可以将 tmp 声明为T并使用它:

 T tmp = a[j];
 a[j] = a[j - 1];
 a[j - 1] = tmp;

而不是 Comparable tmp,使用 T tmp,我认为应该可以解决它。

Things to note down in your code:代码中需要注意的事项:

  • Your definition of T is recursive.您对 T 的定义是递归的。 May be work out an interface if you need to.如果需要,可能会制定一个接口。
  • Your assignment is wrong as clearly pointed out by the compiler!正如编译器明确指出的那样,您的分配是错误的! :-) :-)

    Comparable tmp = a[j];可比 tmp = a[j];

this will work, because this is true and correct.这会奏效,因为这是正确的。 Since T extends Comparable, T is-a Comparable.由于 T 扩展了 Comparable,T是一个Comparable。

  a[j - 1] = tmp;

This will not work, because you are trying to assign a superclass instance to a subclass instance.这将不起作用,因为您正在尝试将超类实例分配给子类实例。 Comparable is not guaranteed to have T behavior. Comparable 不保证有 T 行为。 Hence the error.因此错误。

You can try and parameterize your class in which this function lies.您可以尝试参数化此函数所在的类。 Use that parameter to define T. Again, You may need to work with interfaces.使用该参数来定义 T。同样,您可能需要使用接口。 Unless we know more about the other related design goals, difficult to advice.除非我们更多地了解其他相关的设计目标,否则很难提出建议。 Code wise, the error is correct and justified.代码明智,错误是正确和合理的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM