Java“对compareTo(T)的未检查的调用作为原始类型java.lang.Comparable的成员” [英] Java "unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable"
问题描述
我试图在Java中实现一个排序列表作为一个简单的练习。为了使其具有通用性,我有一个 add(Comparable obj)
,所以我可以将它用于任何实现Comparable接口的类。
但是,当我在代码中的任何地方使用 obj.compareTo(...)
,我得到unchecked call to compareTo(T)作为编译器的原始类型java.lang.Comparable
的成员(使用 -Xlint:unchecked
选项)。该代码工作得很好,但我无法弄清楚如何摆脱那个恼人的信息。
任何提示?
Comparable< T>
是一个通用接口,其中类型参数 T
指定了此对象可以比较的对象的类型为了正确使用 Comparable< T>
,你需要使你的排序列表具有通用性,来表达一个限制,即你的列表存储了可以相互比较的对象,如下所示:
public class SortedList< T扩展了Comparable< ;? super T>> {
public void add(T obj){...}
...
}
I'm trying to implement a sorted list as a simple exercise in Java. To make it generic I have an add(Comparable obj)
so I can use it with any class that implements the Comparable interface.
But, when I use obj.compareTo(...)
anywhere in the code I get "unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable"
from the compiler (with -Xlint:unchecked
option). The code works just fine but I can't figure out how to get rid of that annoying message.
Any hints?
In essence, this warning says that Comparable
object can't be compared to arbitrary objects. Comparable<T>
is a generic interface, where type parameter T
specifies the type of the object this object can be compared to.
So, in order to use Comparable<T>
correctly, you need to make your sorted list generic, to express a constraint that your list stores objects that can be compared to each other, something like this:
public class SortedList<T extends Comparable<? super T>> {
public void add(T obj) { ... }
...
}
这篇关于Java“对compareTo(T)的未检查的调用作为原始类型java.lang.Comparable的成员”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!