在看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泛型的知识点,然后就自己测试一下,以下是测试代码:
- 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>>()都报错