【发布时间】:2013-08-21 12:55:46
【问题描述】:
在使用链表(实际上是内部类Node)实现优先级队列时,我将insert() 和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
有人可以解释为什么会这样吗?
【问题讨论】:
-
因为不是Item是可以和Item比较的东西,不一样
-
Type erasure, overriding and generics 可能重复使用
for(Node<Item> t=head.next;t!=null;t=t.next){将消除类型不匹配错误。
标签: java generics linked-list