public class Node<E> {
private E data;
private Node<E> next;
public Node<E>(){
next = null;
}
public Node(E dataIn){
data = dataIn;
}
}
///
class LinkedList<E>{
public void insert(E dataIn){
if(ctr != 0){
Node<E> temp = new Node<E>(dataIn);
Node<E> cursor = head;
Node<E> prev = cursor;
while(cursor != null && cursor.data.compareTo(dataIn) < 0){
prev = cursor;
cursor = cursor.next;
}
prev.next = temp;
temp.next = cursor;
}
else
add(dataIn);
++ctr;
}
}
在我的插入函数中,如何让Java知道cursor.data与dataIn是同一类型?(假设它们都是Integers)对不起,对于这个愚蠢的问题,我深表歉意。我是菜鸟,我不知道在哪里编写“ compareTo”函数,因为我使用的是Integer而不是自定义数据类型。因此,当我编译代码时,会出现此错误
required: E#1
found: no arguments
reason: actual and formal argument lists differ in length
where E#1,E#2 are type-variables:
E#1 extends Object declared in class LinkedList
E#2 extends Object declared in class Node
LinkedList.java:34: error: cannot find symbol
while(cursor != null && cursor.data.compareTo(dataIn) < 0){
^
symbol: method compareTo(E#1)
location: variable data of type E#2
where E#1,E#2 are type-variables:
E#1 extends Object declared in class LinkedList
E#2 extends Object declared in class Node
提前感谢您的关注!!
答案 0 :(得分:3)
通过以下方式定义列表类
public class LinkedList<E extends Comparable<E>> {
private static class Node<E> {
,并确保Node
类是静态嵌套的(在这种情况下可以为private
,package-private
)。之后,可以将实现Comparable
的任何类型添加到链接列表中。