如何使用Comparable比较链表中的通用节点?

has*_*ash 6 java generics priority-queue sortedlist

我正在使用链接列表实现排序列表.我的节点类看起来像这样

public class Node<E>{
    E elem;
    Node<E> next, previous;
}
Run Code Online (Sandbox Code Playgroud)

在排序列表类中,我有add方法,我需要根据compareTo()方法的实现比较泛型对象,但是我得到这个语法错误"方法compareTo(E)未定义类型E".我尝试在Node中实现compareTo方法,但是我不能调用任何对象的方法,因为E是泛型类型.这是add(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

        }
}
Run Code Online (Sandbox Code Playgroud)

这是一个对象实现compareTo方法

public class Patient implements Comparable<Patient>{
    public int compareTo(Patient that)
    {
        return (this.getPriority() <= that.getPriority() ? 1 : 0 );
    }
}
Run Code Online (Sandbox Code Playgroud)

Boh*_*ian 6

将E绑定到可比较:

public class Node<E extends Comparable<E>>{
    E elem;
    Node<E> next, previous;
}
Run Code Online (Sandbox Code Playgroud)

它现在将编译.