【发布时间】:2021-03-12 17:38:30
【问题描述】:
我有以下代码,如何使用原始类型的 compareTo 方法:
public class mySortertedList<T extends Comparable<T>> extends myLinkedList<T> {
class Node {
Node next = null;
T data;
Node (T x) {
data = x;
}
}
public int compareTo (T Obj) {
return this.compareTo(Obj);
}
基本上我所拥有的是一个排序的链表,它根据 compareTo 方法将值添加到列表中。如何确保 compareTo 适用于原始类型,至少是整数?非常感谢任何帮助!
编辑:为了澄清,这里有更多代码: 主程序:
public static void main(String[] args) {
newList.addTo(4);
newList.addTo(1337);
newList.addTo(30);
newList.addTo(15);
}
我还有其他方法,例如 get(int index)、remove(),即删除列表中的最后一个元素。这里是mySortertList
private Node start = null;
public void addTo(T x) {
Node newNode = new Node(x);
Node pointer = start;
if (start == null) {
start = newNode;
} else if (size()==1){
if (newNode.data.compareTo(start.data)<0) {
newNode.next= start;
start = newNode;
} else {
start.next= newNode;
}
} else {
boolean valuePlaced= false;
Node pointer2= start.next;
while (pointer2 !=null) {
if (newNode.data.compareTo(pointer.data)<0) {
newNode.next= start.next;
start.next = newNode;
valuePlaced = true;
} else if (newNode.data.compareTo(pointer2.data)<0) {
pointer = newNode;
new.next= pointer2;
valuePlaced = true;
}
pointer = pointer.next;
pointer2 = pointer2.next;
}
if (valuePlaced == false) {
pointer.next= newNode;
}
}
}
【问题讨论】:
-
1) 其中 exactly 是您的原语 2) 不要将字符串与
==进行比较 3) 这个问题没什么意义 -
Eugene,当我在主程序中创建列表时,我将其设置为 mySortedList
,并将 int 值传递给 compareTo 方法,例如 this.data.compareTo(x.data ),但由于 compareTo 仅适用于类,而不适用于原语,因此它不起作用。 -
另外,如果我使用 == 比较 String 的 if 语句是因为我确切知道 (Object)Obj.getClass().getName() 是什么,如果 Obj 是原始类型的实例诠释。我使用它是因为我不能在通用对象上调用 instanceof int。
-
您能否提供几行代码,您可以在其中 (1) 声明整数列表,(2) 实现方法 compareTo ?这里似乎在 Node 类或 mySortertedList 类中。还不够清楚。
-
g.momo 刚刚添加了主程序和addTo方法