了解Java中的泛型和可比性

了解Java中的泛型和可比性,java,generics,comparable,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 exte

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

我试图构建我认为最基本的实现,但它仍然不起作用

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());
    }   
}
这是怎么回事

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

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

public int isSorted(){ 
    return thing1.compareTo(thing2);  // thing1 and thing2 are comparable now
}   
public int isSorted(){
返回thing1.compareTo(thing2);
}
不能有对类定义的泛型类型参数施加新约束的方法。你必须申报

public class GenericPair<T extends Comparable<T>> {
   public int isSorted() {
     return thing1.compareTo(thing2);
   }
}
公共类泛型对{
公共整数排序(){
返回thing1.compareTo(thing2);
}
}
public int isSorted(){
返回thing1.compareTo(thing2);
}
不能有对类定义的泛型类型参数施加新约束的方法。你必须申报

public class GenericPair<T extends Comparable<T>> {
   public int isSorted() {
     return thing1.compareTo(thing2);
   }
}
公共类泛型对{
公共整数排序(){
返回thing1.compareTo(thing2);
}
}

问题是整个类的泛型
T
不知道
比较方法。即使您为这个方法声明了
,您也只是创建了一个新的
T
,它对类隐藏了泛型
T
的定义

解决方案可以在类本身中声明
T

class GenericPair<T extends Comparable<T>> {
    public int isSorted() {
        return thing1.compareTo(thing2);
    }
}
类泛型对{
公共整数排序(){
返回thing1.compareTo(thing2);
}
}

问题是整个类的泛型
T
不知道
比较方法。即使您为这个方法声明了
,您也只是创建了一个新的
T
,它对类隐藏了泛型
T
的定义

解决方案可以在类本身中声明
T

class GenericPair<T extends Comparable<T>> {
    public int isSorted() {
        return thing1.compareTo(thing2);
    }
}
类泛型对{
公共整数排序(){
返回thing1.compareTo(thing2);
}
}

这是最正确的,它在类声明中这是最正确的,它在类声明中虽然您可以有一个方法隐藏类定义的泛型类型参数。是的,我只是指出这就是这里发生的事情。虽然你可以有一个方法隐藏类定义的泛型类型参数。是的,我只是指出这就是这里发生的事情。