简体   繁体   English

问题 <T extends Comparable<? super T> &gt;

[英]Issue with <T extends Comparable<? super T>>

I have a HeapInterface, and a Heap class with an array-based implementation. 我有一个HeapInterface和一个基于数组的实现的Heap类。 I'm trying to make a Heap of the class Integers, but I'm getting the following error: 我正在尝试制作Integers类的堆,但是出现以下错误:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;
at HeapArray.<init>(HeapArray.java:16)
at HeapArray.<init>(HeapArray.java:10)
at Test.main(Test.java:5)

I'll provide the declaration of each class, the constructors, and the test method that produced the error in hopes someone can explain my error... 我将提供每个类的声明,构造函数和产生错误的测试方法,以希望有人可以解释我的错误...

public interface HeapInterface<T extends Comparable<? super T>> {...}

public class HeapArray<T extends Comparable<? super T>> implements HeapInterface<T> {
   private T[] heap;
   private static final int DEFAULT_CAPACITY = 10;
   private int numberOfEntries;

   public HeapArray() {
      this(DEFAULT_CAPACITY);
   }//end default constructor

   public HeapArray(int capacity) {
      numberOfEntries = 0;
      @SuppressWarnings("unchecked")
      T[] tempHeap = (T[]) new Object[capacity];
      heap = tempHeap;
   }//end alternative constructor

   ...
}

public class Test {

   public static void main(String[] args) {
      HeapInterface<Integer> h = new HeapArray<Integer>();

      for(int i = 0; i < 16; i++)
         h.add(i);

      System.out.println(h);
   }
}

Any ideas? 有任何想法吗?

You can't cast an Object[] to a T[] whilst asserting that T is comparable as an Object is not comparable. 在断言T是可比较的时,您不能将Object []强制转换为T [],因为Object是不可比较的。 Try creating a Comparable[] and casting it to a T[] : 尝试创建一个Comparable[]并将其转换为T[]

  T[] tempHeap = (T[]) new Comparable[capacity];

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

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