繁体   English   中英

了解Java中的泛型和可比性

[英]Understanding generics and comparable in Java

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

我试图构建我认为是此方法的最基本实现,但仍无法正常工作。

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());
    }   
}

我的理解是>要求无论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

这里发生了什么?

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

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

因此,您应该声明您的类的type参数是可比较的:

class GenericPair<T extends Comparable<T>>

现在:

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

问题在于整个类的通用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);
    }
}
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);
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM