Java 链表的比较对象
Java compareTo for LinkedList
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 的类型相同?(假设它们都是整数)抱歉,我为这个愚蠢的问题道歉。我是菜鸟,我不知道在哪里写 '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
提前感谢您的关注!
按以下方式定义列表class
public class LinkedList<E extends Comparable<E>> {
private static class Node<E> {
并确保 Node
class 是嵌套静态的(在这种情况下可以是 private
、package-private
)。之后就可以将实现 Comparable
的任何类型添加到链表中。
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 的类型相同?(假设它们都是整数)抱歉,我为这个愚蠢的问题道歉。我是菜鸟,我不知道在哪里写 '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
提前感谢您的关注!
按以下方式定义列表class
public class LinkedList<E extends Comparable<E>> {
private static class Node<E> {
并确保 Node
class 是嵌套静态的(在这种情况下可以是 private
、package-private
)。之后就可以将实现 Comparable
的任何类型添加到链表中。