在使用链表(实际上是一个内部类Node
)实现优先级队列时,我对insert()
and方法进行了如下编码。它使用惰性方法保持项目无序,然后仅在发生or调用max()
时才通过它们搜索最大元素。max()
deleteMax()
public class LinkedListMaxPQ<Item extends Comparable<Item>>{
private int N;
private Node head;
public void insert(Item item) {
Node old = head;
head = new Node();
head.item = item;
head.next = old;
N++;
}
public Item max() {
Item maxitem = (Item) this.head.item;
for(Node t=head.next;t!=null;t=t.next){
if(gt(t.item,maxitem)){
maxitem = (Item) t.item;
}
}
return maxitem;
}
private boolean gt(Comparable x,Comparable y){
return x.compareTo(y) > 0;
}
private class Node<Item extends Comparable<Item>>{
Item item;
Node next;
}
}
我想知道为什么我需要演员表Item maxitem = (Item) this.head.item
?由于该类使用泛型类型Item which extends Comparable
并且内部类也使用 Item extends Comparable ,因此人们会认为这样的强制转换是不必要的。
如果我省略演员表
Item maxitem = this.head.item;
编译器会抱怨类型不匹配
类型不匹配:无法从 Comparable 转换为 Item
有人可以解释为什么会这样吗?