Java“对compareTo(T)的未检查的调用作为原始类型java.lang.Comparable的成员” [英] Java "unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable"

查看:1575
本文介绍了Java“对compareTo(T)的未检查的调用作为原始类型java.lang.Comparable的成员”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Java中实现一个排序列表作为一个简单的练习。为了使其具有通用性,我有一个 add(Comparable obj),所以我可以将它用于任何实现Comparable接口的类。



但是,当我在代码中的任何地方使用 obj.compareTo(...),我得到unchecked call to compareTo(T)作为编译器的原始类型java.lang.Comparable的成员(使用 -Xlint:unchecked 选项)。该代码工作得很好,但我无法弄清楚如何摆脱那个恼人的信息。



任何提示?

Comparable 对象不能与任意对象进行比较。

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆