理解泛型和Java中的可比性

时间:2014-04-01 16:18:17

标签: java generics comparable

我正在努力创建要求其元素具有可比性的通用数据类型。

我试图构建我认为最基本的实现,但它仍然无效。

public class GenericPair<T> {
    T thing1;
    T thing2;

    public GenericPair(T thing1, T thing2){
        this.thing1 = thing1;
        this.thing2 = thing2;
    }   


    public <T extends Comparable<T>> int isSorted(){ 
        return thing1.compareTo(thing2);
    }   

    public static void main(String[] args){
        GenericPair<Integer> onetwo = new GenericPair<Integer>(1, 2); 
        System.out.println(onetwo.isSorted());
    }   
}

我的理解是&gt;要求无论何种类型的T结束,它必须实现可比较,因此必须具有compareTo()函数。在这种情况下,整数应该具有此功能吗?

我收到错误:

GenericPair.java:15: error: cannot find symbol
    return thing1.compareTo(thing2);
                 ^
    symbol:   method compareTo(T)
    location: variable thing1 of type T
    where T is a type-variable:
    T extends Object declared in class GenericPair

这里发生了什么?

3 个答案:

答案 0 :(得分:3)

public <T extends Comparable<T>> int isSorted(){ 
    return thing1.compareTo(thing2);
}  

这个新T隐藏了您的类的类型参数(也称为T)。它们是两种不同的类型! thing1thing2是您的泛型类型的实例,这些类型不一定具有可比性。

所以,你应该声明你的类的类型参数是可比的:

class GenericPair<T extends Comparable<T>>

现在:

public int isSorted(){ 
    return thing1.compareTo(thing2);  // thing1 and thing2 are comparable now
}   

答案 1 :(得分:1)

问题是全班的通用T并不知道compareTo方法。即使您为此单一方法声明<T extends Comparable<T>>,您也只是创建一个新的T来隐藏类中通用T的定义。

解决方案可能是在类本身中声明T extends Comparable<T>

class GenericPair<T extends Comparable<T>> {
    public int isSorted() {
        return thing1.compareTo(thing2);
    }
}

答案 2 :(得分:0)

public <T extends Comparable<T>> int isSorted(){ 
    return thing1.compareTo(thing2);
}

您不能拥有对类定义的泛型类型参数施加新约束的方法。你必须声明

public class GenericPair<T extends Comparable<T>> {
   public int isSorted() {
     return thing1.compareTo(thing2);
   }
}