<T extends Comparable<? super T>>
阿新 • • 發佈:2017-05-23
tool start ted tools 源代碼 static 了解 -m ron
在看Collections源代碼中,看到如下代碼:[java] view plain copy
- 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]);
- }
- }
有點郁悶,不知道一下代碼是啥意思[java] view plain copy
- <T extends Comparable<? super T>>
百度後了解了這是Java泛型的知識點,然後就自己測試一下,以下是測試代碼:[java] view plain copy
- /**
- * 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>>()都報錯
<T extends Comparable<? super T>>