我正在使用鏈接列表實現一個排序列表。我的節點類看起來像這樣如何使用Comparable比較鏈表中的通用節點?
public class Node<E>{
E elem;
Node<E> next, previous;
}
在排序列表類我有add方法,在這裏我需要根據其實施的compareTo()方法來比較通用的對象,但我得到這個語法錯誤 「的方法compareTo(E)對於E類型是未定義的「。我試過在Node中實現compareTo方法,但是我不能調用任何對象的方法,因爲E是泛型類型。 這裏是添加(E elem)方法的未完成體。
public void add(E elem)
{
Node<E> temp = new Node<E>();
temp.elem = elem;
if(isEmpty()) {
temp.next = head;
head.previous = temp;
head = temp;
counter++;
}else{
for(Node<E> cur = head; cur.next != null ; cur= cur.next) {
**if(temp.elem.comparTo(cur.elem)) {**
//do the sort;
}/*else{
cur.previous = temp;
}*/
}
//else insert at the end
}
}
這裏是implemnting compareTo方法
public class Patient implements Comparable<Patient>{
public int compareTo(Patient that)
{
return (this.getPriority() <= that.getPriority() ? 1 : 0);
}
}
謝謝你們。現在做了這些改變之後,我得到這個錯誤 「三寸不匹配:類型E是不是有界參數的有效替代品>類型\t 節點的」 在該行 節點溫度= new Node (); temp.elem = elem; –
hash
2011-06-15 10:41:08