找不到符号/无法使用泛型中的 ArrayList 将对象转换为可比对象

cannot find symbol / cannot convert object to comparable using ArrayList in generics

在这个程序中,我在 Java 中使用数组列表创建堆优先级队列。 我会尽量保持代码裸露,以帮助更轻松地解决问题。

本质上,我已经为 heapAPI 定义了一个接口并在堆 class 中实现了它。堆构造函数应该通过定义对象的数组列表来构造堆对象。在这里,我想传递 PCB class 的对象(要进入优先级队列的作业)。但是,当我传递这些对象时,我无法通过数组列表访问它们。

下面附上了 HeapAPI、Heap class 和 PCB class 的代码。

HeapAPI.java

public interface HeapAPI<E extends Comparable<E>>
{
     boolean isEmpty();
     void insert(E item);
     E remove() throws HeapException;
     E peek() throws HeapException;
     int size();
}

Heap.java

public class Heap<E extends Comparable<E>> implements HeapAPI<E>
{
     private ArrayList<E> tree;

     public Heap()
     {
          tree = new ArrayList<>();
     }

// don't believe the rest of the class is necessary to show
}

PCB.java

public class PCB implements Comparable<PCB>
{
     private int priority;

     // various private variables

     public PCB()
     {
       priority = 19;
       // instantiated variables
     }

    // don't believe the rest of the code is necessary
    // the one specific function of PCB I use follows

     public int getPriority()
     {
          return priority;
     }
}

在将PCB对象插入Heap对象的数组列表后,我尝试了以下主要方法通过ArrayList调用PCB对象的函数。

Main.java

public class Main 
{
     public static void main(String[] args) throws HeapException
     {
          Heap temp = new Heap();
          PCB block = new PCB();
          PCB block1 = new PCB();
          PCB block2 = new PCB();

          temp.insert(block);
          temp.insert(block1);
          temp.insert(block2);

          block.getPriority();

          // does not work
          int num = temp.peek().getPriority();
          //does not work
          num = temp.get(0).getPriority();
}

我得到的错误是程序找不到符号:方法 getPriority()。

[另外,导入java.util.ArrayList;在每个文件中调用]

我一直在努力学习和应用泛型,但现在卡住了。

如果我不清楚任何事情,我可以轻松添加更多代码或澄清问题。

如有任何帮助,我们将不胜感激。

谢谢!

将堆声明更改为

Heap<PCB> temp = new Heap<>();

现在您的编译器知道 Heap 包含 PCB 对象,它期望与没有 getPriority() 方法的 return 相当。

这是问题所在:

Heap temp = new Heap();

您有一个泛型 Heap class 但在这里您创建的它没有泛型。这是 Raw Types.

的示例

类似于:

Heap<PCB> temp = new Heap<>();

应该可以。