gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:54:37 26 4
gpt4 key购买 nike

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

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

下面附有HeapAPI、Heap类和PCB类的代码。

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

堆.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 temp = new Heap();

您有一个通用的Heap类,但在这里您创建它时没有它的泛型。这是 Raw Types 的示例.

类似于:

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

应该可以。

关于java - 找不到符号/无法使用泛型中的 ArrayList 将对象转换为可比较的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46316140/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com