在优先级队列中无法识别覆盖的 compareTo()

Overriden compareTo() not recognised in priority queue

我已经在磁盘 class 中实现了 compareTo() ,即使我在 main 中使用它时它工作正常,但当我尝试编译使用相同的优先级队列时它给了我以下错误方法:

MaxPQ.java:113: 错误:二元运算符 '>=' 的错误操作数类型 如果 ((Disk)heap[i].compareTo((Disk)heap[max]) >= 0)

知道为什么吗?

代码如下:


public class Disk implements Comparable <Disk>{

    public static int count = 0;
    public int id;
    //public Node folders;
    public int freeSpace;

    public Disk(){
        count++;
        id = count;
    }

    public int getFreeSpace(){
        return freeSpace;
    }

    @Override
    public int compareTo(Disk d){
         return Integer.compare(this.getFreeSpace(), d.getFreeSpace());
    }


}

并且:

public class MaxPQ<Disk> {


    private Disk[] heap; // the heap to store data in
    private int size; // current size of the queue
    //private Comparator comparator; // the comparator to use between the objects

    private static final int DEFAULT_CAPACITY = 4; // default capacity
    private static final int AUTOGROW_SIZE = 4; // default auto grow


    //public MaxPQ(Comparator comparator) {
    public MaxPQ() {
        this.heap = (Disk[])new Object[DEFAULT_CAPACITY + 1];
        this.size = 0;
        //this.comparator = comparator;
    }

    private void sink(int i) {
        // determine left, right child
        int left = 2 * i;
        int right = left + 1;

        // if 2*i > size, node i is a leaf return
        if (left > size)
            return;

        // while haven't reached the leafs
        while (left <= size) {
            // Determine the largest child of node i
            int max = left;
            if (right <= size) {
                if (heap[left].compareTo(heap[right]) < 0)
                    max = right;
            }

            // If the heap condition holds, stop. Else swap and go on.
            // child smaller than parent
            if ((Disk)heap[i].compareTo((Disk)heap[max]) >= 0)
                return;
            else {
                swap(i, max);
                i = max;
                left = i * 2;
                right = left + 1;
            }
        }
    }

问题是您将 Disk 用作通用类型参数,然后尝试将其用作 class。

看起来 MapPQ 不应该是通用的 class。它专门使用 Disk。所以我会:

  1. 更改声明,使其不通用;
  2. 使用new Disk[DEFAULT_CAPACITY + 1]创建heap
  3. 并删除所有这些转换

如果您确实希望 Disk 是通用的(惯例是使用单个字母,而不是单词;我将使用 T,它绝大多数是用于第一个通用类型的字母参数),在实例化 MapPQ 时,您必须让调用者传入它应该用于数组的 Class 实例。请参阅 this question's answers 了解如何执行此操作,但大致为:

public MapPQ(Class<T> cls) {
    ths.heap = (T[])Array.newInstance(cls, DEFAULT_CAPACITY + 1);
}

(或者将 heap 声明为 Object[] 并保留所有的转换,但它很容易出错。)