java - 泛型堆中的比较运算符

标签 java heap

对于我的数据结构类,我们的作业是创建一个通用堆 ADT。在 siftUp() 方法中,我需要进行比较,如果父级较小,我需要进行交换。我遇到的问题是比较运算符对泛型类型无效。我相信我需要使用 Comparable 接口(interface),但从我读到的内容来看,与数组一起使用并不是一个好主意。我也搜索了这个网站,我找到了与这篇文章相关的好信息,但它们都没有帮助我找到解决方案

我删除了一些不相关的代码 谢谢

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

最佳答案

从技术上讲,您正在使用项目上的类似接口(interface),而不是数组。特别是数组中的一项。我认为这里最好的解决方案是在构造函数中接受一个比较器,用户可以传递该比较器来比较他的通用对象。

Comparator<E> comparator;
public HeapQueue(int a_highest, Comparator<E> compare)
{
    this.comparator = compare;

然后,您可以将该比较器存储在成员函数中并使用

if (comparator.compare(data[parentIndex],data[nodeIndex]) < 0)  

代替小于运算符。

关于java - 泛型堆中的比较运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5751448/

相关文章:

java - 定义从 java 中的 json 字符串中提取多个日期的模式的问题

java - 使用正确数量的参数从 Batch 脚本运行 Java 程序

algorithm - CLRS 的 Fibonacci Heap size(x) 分析有缺陷?

java - 斐波那契堆问题

algorithm - Max-Heapify 二叉树

java - 为任何可比较集合编写排序方法 (Java)

java - Apache POI无法在Linux中生成Excel

algorithm - 堆排序的目的是什么?

基于 Java 枚举的状态机 (FSM) : Passing in events

c - 删除二叉堆中的最顶层元素