既然我已经实现了这个方法,为什么Java说“无法解析方法getPriority()”?
我创建了一个包含QueueItem
对象的优先级队列。但是,即使我已经在QueueItem
类中实现了getPriority()
,它仍然在PriorityQueue
类的方法insert()
中表示cannot resolve method getPriority()
这是我的PriorityQueue
课程:
public class PriorityQueue<QueueItem> implements Iterator<QueueItem> {
private int maxSize;
private int size;
private Map<Integer, List<QueueItem>> pq;
public PriorityQueue(int maxSize) {
if (maxSize < 0) throw new IllegalArgumentException();
this.maxSize = maxSize;
pq = new HashMap<Integer, List<QueueItem>>();
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
public void insert (QueueItem item) {
int priority = item.getPriority(); //here is where the problem occured
// pq.get(priority)
}
}
这是我的QueueItem
类:
public class QueueItem implements Comparable{
private int priority;
private Object value;
public QueueItem() {
priority = -1;
value = null;
}
public QueueItem(int priority, Object value) {
this.priority = priority;
this.value = value;
}
public int getPriority() {
return priority;
}
public Object getValue() {
return value;
}
public int compareTo(Object o) {
if (!(o instanceof QueueItem)) throw new ClassCastException();
if (((QueueItem)o).getPriority() == -1) throw new NullPointerException();
return priority - ((QueueItem) o).getPriority();
}
}
如您所见,方法getPriority()
只返回一个整数优先级
如果有人能指出我犯的错误,我将提前表示感谢。谢谢
# 1 楼答案
哦。它正盯着我的脸
您在这里声明了一个类型变量,其名称与隐藏它的类
QueueItem
相同所以我想你只是想把它去掉:
如果您希望
PriorityQueue
是泛型的,那么我不确定您需要做什么来修复它。也许你会想要这样的东西:作为旁注,使用原始类型
Comparable
isn't good。即使是非泛型的class QueueItem
,您也应该有implements Comparable<QueueItem>