首页 > 解决方案 > 在优先级队列中无法识别覆盖的 compareTo()

问题描述

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

MaxPQ.java:113:错误:二元运算符 '>=' 的错误操作数类型 if ((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;
            }
        }
    }

标签: javacomparatorpriority-queuecompareto

解决方案


问题是您将Disk其用作泛型类型参数,然后尝试像使用类一样使用它。

它看起来不MapPQ应该是一个泛型类。它Disk专门使用。所以我会:

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

如果您确实想要Disk通用(约定是使用单个字母,而不是单词;我将使用T绝大多数用于第一个泛型类型参数的字母),在实例化时MapPQ您必须让调用者传入Class它应该用于数组的实例。请参阅此问题的答案以了解如何执行此操作,但大致如下:

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

(或者声明heapObject[]并保留你所有的演员表,但这很容易出错。)


推荐阅读