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;
}
}在我的insert函数中,我如何让Java知道cursor.data与dataIn的类型相同?(假设它们都是整数)对不起,我为这个愚蠢的问题道歉。我是一个菜鸟,我不知道在哪里编写'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提前感谢您的关注。
发布于 2018-09-21 10:27:32
以下列方式定义列表类
public class LinkedList<E extends Comparable<E>> {
private static class Node<E> {并确保Node类是嵌套静态的(在本例中可以是private,package-private )。在此之后,可以将实现Comparable的任何类型添加到链接列表中。
https://stackoverflow.com/questions/52441379
复制相似问题