【发布时间】:2021-09-15 21:28:56
【问题描述】:
我最近在 10 年后回到 Java,但我已经很生疏了。我正在尝试运行我拥有的一些基本排序列表代码。此代码用于编译和运行,但现在我收到以下警告:
.\LinkedList.java:30: warning: [unchecked] unchecked call to compareTo(T) as a member of the raw type Comparable
return _data.compareTo( ((Node)n)._data );
^
where T is a type-variable:
T extends Object declared in interface Comparable
这是引发警告的代码:
static protected class Node implements Comparable
{
public Node _next;
public Comparable _data;
protected Node(Comparable data, Node next)
{
_next = next;
_data = data;
}
public int compareTo(Object n)
{
return _data.compareTo( ((Node)n)._data );
}
public String toString()
{
return _data.toString();
}
} // end Node class
我的理解是我不能再在原始类型上使用 compareTo(),但我不确定如何修复它。欢迎任何帮助。 堆栈溢出也是新的,所以如果我做错了或错过了已经回答的地方,请原谅我。
【问题讨论】:
-
看the documentation of Comparable。看看它是如何定义为
Comparable<T>的?因此,您需要写protected class Node implements Comparable<Node>。 -
如果真的过了 10 年,您可能使用的是 Java 7,甚至可能是 Java 6。无论是在语言上还是在库中,都进行了许多增量改进。值得研究每个版本的更改列表,以了解消除大量过去需要的样板代码的方法。
标签: java linked-list comparable compareto unchecked