我已经在Disk类中实现了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
用作泛型类型参数,然后尝试像类一样使用它。
[MapPQ
看起来不是通用类。具体使用Disk
。所以我会:
new Disk[DEFAULT_CAPACITY + 1]
创建heap
;如果您确实想让Disk
是通用的(惯例是使用单个字母,而不是单词;我将使用T
,这绝对是用于第一个通用类型参数的字母),当实例化[C0 ],您必须将调用方传递到应用于数组的MapPQ
实例中。具体操作请参见Class
,但大致为:
this question's answers
((或将public MapPQ(Class<T> cls) {
ths.heap = (T[])Array.newInstance(cls, DEFAULT_CAPACITY + 1);
}
声明为heap
并保留所有演员表,但这容易出错。)