在看Collections源代码中,看到如下代码:
public static <T extends Comparable<? super T>> void sort(List<T> list) { Object[] a = list.toArray(); Arrays.sort(a); ListIterator<T> i = list.listIterator(); for (int j=0; j<a.length; j++) { i.next(); i.set((T)a[j]); }}
有点郁闷,不知道一下代码是啥意思
<T extends Comparable<? super T>>
百度后了解了这是Java泛型的知识点,然后就自己测试一下,以下是测试代码:
/** * Created by CSH on 12/7/2015. *///测试泛型public class TestGeneric { @Test public void test01(){ new A<If<Father>>(); //不报错 new B<If<Father>>(); //不报错 new C<If<Father>>(); //不报错 new A<If<Child>>(); //报错 new B<If<Child>>(); //报错 new C<If<Child>>(); //不报错 new A<If<GrandFather>>(); //不报错 new B<If<GrandFather>>(); //报错 new C<If<GrandFather>>(); //报错 }}class GrandFather {}class Father extends GrandFather{}class Child extends Father {}interface If<T>{ void doSomething();}class A <T extends If<? super Father>> {}class B <T extends If<Father>> {}class C <T extends If<? extends Father>>{}
结果是:
这例子可以区分super和extends这2个关键字的区别
super:<? super Father> 指的是Father是上限,传进来的对象必须是Father,或者是Father的父类,因此 new A<If<Child>>()会报错,因为Child是Father的子类
extends:<? extends Father> 指的是Father是下限,传进来的对象必须是Father,或者是Father的子类,因此 new C<If<GrandFather>>()会报错,因为GrandFather是Father的父类
<Father> 指的是只能是Father,所以new B<If<Child>>()和 new B<If<GrandFather>>()都报错
知乎上的网友解释链接:点击打开链接