对于我的数据结构类,我们的作业是创建一个通用堆 ADT。在 siftUp() 方法中,我需要进行比较,如果父级较小,我需要进行交换。我遇到的问题是比较运算符对泛型类型无效。我相信我需要使用 Comparable 接口,但从我读到的内容来看,与数组一起使用并不是一个好主意。我也搜索了这个网站,我找到了与这篇文章相关的好信息,没有一个能帮助我找到解决方案
我删除了一些不相关的代码谢谢
public class HeapQueue<E> implements Cloneable {
private int highest;
private Integer manyItems;
private E[] data;
public HeapQueue(int a_highest) {
data = (E[]) new Object[10];
highest = a_highest;
}
public void add(E item, int priority) {
// check to see is priority value is within range
if(priority < 0 || priority > highest) {
throw new IllegalArgumentException
("Priority value is out of range: " + priority);
}
// increase the heaps capacity if array is out of space
if(manyItems == data.length)
ensureCapacity();
manyItems++;
data[manyItems - 1] = item;
siftUp(manyItems - 1);
}
private void siftUp(int nodeIndex) {
int parentIndex;
E tmp;
if (nodeIndex != 0) {
parentIndex = parent(nodeIndex);
if (data[parentIndex] < data[nodeIndex]) { <-- problem ****
tmp = data[parentIndex];
data[parentIndex] = data[nodeIndex];
data[nodeIndex] = tmp;
siftUp(parentIndex);
}
}
}
private int parent(int nodeIndex) {
return (nodeIndex - 1) / 2;
}
}