有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java问题与<T扩展可比<?超级T>>

我有一个HeapInterface和一个基于数组实现的Heap类。我试图创建一个类整数堆,但出现以下错误:

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)

我将提供每个类的声明、构造函数和产生错误的测试方法,希望有人能解释我的错误

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);
   }
}

有什么想法吗


共 (1) 个答案

  1. # 1 楼答案

    不能将对象[]强制转换为t[],同时断言t是可比的,因为对象是不可比的。尝试创建一个Comparable[]并将其强制转换为T[]

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