Java:删除“Comparable是原始类型”警告

时间:2011-08-10 09:33:46

标签: java warnings comparable raw-types

假设我有一个名为foo的方法,将2个Object作为参数。两个对象属于同一类型,并且都实现了可比较的接口。

void foo(Object first, Object second){

    if (!first.getClass().isInstance(second))   //first and second of the same type
        return;

    Comparable firstComparable = (Comparable)first;  //WARNING
    Comparable secondComparable = (Comparable)second;  //WARNING

    int diff = firstComparable.compareTo(secondComparable);  //WARNING
}

前两个警告是:

  

可比较是原始类型。对泛型类型的引用可比较   应该参数化

最后警告:

  

类型安全:方法compareTo(Object)属于原始类型   可比。对泛型类型的引用应该是   参数

如何重构我的代码以删除这些警告?

编辑: 我可以不改变foo方法的签名吗?

5 个答案:

答案 0 :(得分:13)

你必须告诉编译器它们是相同的类型和可比较的。如果您无法更改签名,则可以添加一种向后兼容的方法。

@SuppressWarnings("unchecked")
static void foo(Object first, Object second) {
    foo((Comparable) first, (Comparable) second);
}

static <T extends Comparable<T>> void foo(T first, T second){
    int diff = first.compareTo(second); // no warning.
}

答案 1 :(得分:3)

无需更改签名即可

    void foo(Object first, Object second){

        if (!first.getClass().isInstance(second)) 
            return;

        Comparable<Object> firstComparable = (Comparable<Object>)first;  
        Comparable<Object> secondComparable = (Comparable<Object>)second; 

        int diff = firstComparable.compareTo(secondComparable);  
    }

但是你还有:
Type safety: Unchecked cast from Object to Comparable<Object>

但没有Comparable is a raw type. References to generic type Comparable<T> should be parameterized
并且没有Type safety: The method compareTo(Object) belongs to the raw type Comparable. References to generic type Comparable<T> should be parameterized

答案 2 :(得分:1)

你必须使用 Comparable<Type>其中Type是实现Comparable的对象。

首先,为什么你的方法参数实例为Objects?如果您确定参数类型相同,则应使用特定类作为参数。如果可以具有类的层次结构,则在层次结构中使类最高。让Object获得一般功能永远不是一个好主意。

答案 3 :(得分:1)

编辑:既然你说你不能改变方法的签名,那么你真的无法逃脱没有不安全(对编译器)演员,以及@SuppressWarnings

@SuppressWarnings("unchecked")
public void foo(final Object first, final Object second) {
    if (!first.getClass().isInstance(second)) // first and second of the
        return;

    Comparable<Object> firstComparable = (Comparable<Object>) first;
    Comparable<Object> secondComparable = (Comparable<Object>) second;
    int diff = firstComparable.compareTo(secondComparable);
}

答案 4 :(得分:0)

添加@SuppressWarnings注释。

@SuppressWarnings("unchecked")
void foo(Object first, Object second){

    if (!first.getClass().isInstance(second))   //first and second of the same type
        return;

    Comparable firstComparable = (Comparable)first;  //WARNING
    Comparable secondComparable = (Comparable)second;  //WARNING

    @SuppressWarnings("unused")
    int diff = firstComparable.compareTo(secondComparable);  //WARNING
}