Java泛型方法边界

Mar*_*gus 8 java generics

以下两行有什么区别?

public static <T extends Comparable<? super T>> int methodX(List<T> data)
public static <T> int methodX(List<? extends Comparable<? super T>> data)
Run Code Online (Sandbox Code Playgroud)

dav*_*vin 2

您的第一个选择是“更严格”的参数化。T意思是,您正在使用一系列限制来定义该类,然后稍后将其与List. 在第二种方法中,参数类T是通用的,没有条件,并且Lists 类参数是根据参数定义的T

第二种方法在语法上也不同,用 a?代替第一个选项的T,因为在参数定义中您没有定义类型参数T而是使用它,因此第二种方法不能那么具体。

由此产生的实际差异是继承之一。您的第一个方法需要是可与自身的超类进行比较的类型,而第二个方法只需与无条件/不相关的进行比较T

public class Person implements Comparable<Number> {
    @Override
    public int compareTo(Number o) {
        return 0;
    }
    public static <T extends Comparable<? super T>> int methodX(List<T> data) {
            return 0;
    }
    public static <T> int methodY(List<? extends Comparable<? super T>> data) {
            return 0;
    }
    public static void main(String[] args) {
        methodX(new ArrayList<Person>()); // stricter ==> compilation error
        methodY<Object>(new ArrayList<Person>());
    }
}
Run Code Online (Sandbox Code Playgroud)

Comparable如果您将of更改Person为能够比较Objector Person(基类的继承树),那么methodX也将起作用。