简体   繁体   中英

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.

The errors are I can't make the assignments.

a[j] is a T , not a Comparable .

You can only put it into a variable of type T .

Your problem is that Comparable is an interface, not a class. you need to create an Object of a class that implements Comparable .

If T implements Comparable , than you can declare tmp as a T and use that:

 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. 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];

this will work, because this is true and correct. Since T extends Comparable, T is-a 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. 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. Unless we know more about the other related design goals, difficult to advice. Code wise, the error is correct and justified.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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