我正在使用链接列表实现排序列表.我的节点类看起来像这样
public class Node<E>{
E elem;
Node<E> next,prevIoUs;
}
在排序列表类中我有add方法,我需要根据compareto()方法的实现来比较泛型对象,但是我得到了这个语法错误
“对于类型E,方法compareto(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
}
}
这是一个对象实现compareto方法
public class Patient implements Comparable<Patient>{
public int compareto(Patient that)
{
return (this.getPriority() <= that.getPriority() ? 1 : 0 );
}
}
解决方法
将E绑定到可比较:
public class Node<E extends Comparable<E>>{
E elem;
Node<E> next,prevIoUs;
}
它现在将编译.