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

问题描述

我试图在Java中实现一个排序列表作为一个简单的练习。为了使其具有通用性,我有一个

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的成员”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 04:59