<T extends Comparable<? super T>>

在看Collections源代码中,看到如下代码:
[java] view plain copy
 
  1. public static <T extends Comparable<? super T>> void sort(List<T> list) {  
  2.     Object[] a = list.toArray();  
  3.     Arrays.sort(a);  
  4.     ListIterator<T> i = list.listIterator();  
  5.     for (int j=0; j<a.length; j++) {  
  6.         i.next();  
  7.         i.set((T)a[j]);  
  8.     }  
  9. }  

有点郁闷,不知道一下代码是啥意思
[java] view plain copy
 
  1. <T extends Comparable<? super T>>  

百度后了解了这是Java泛型的知识点,然后就自己测试一下,以下是测试代码:
[java] view plain copy
 
  1. /** 
  2.  * Created by CSH on 12/7/2015. 
  3.  */  
  4. //测试泛型  
  5. public class TestGeneric {  
  6.   
  7.     @Test  
  8.     public void test01(){  
  9.         new A<If<Father>>();    //不报错  
  10.         new B<If<Father>>();    //不报错  
  11.         new C<If<Father>>();    //不报错  
  12.   
  13.         new A<If<Child>>();     //报错  
  14.         new B<If<Child>>();     //报错  
  15.         new C<If<Child>>();     //不报错  
  16.   
  17.         new A<If<GrandFather>>();   //不报错  
  18.         new B<If<GrandFather>>();   //报错  
  19.         new C<If<GrandFather>>();   //报错  
  20.     }  
  21.   
  22. }  
  23. class GrandFather {  
  24.   
  25. }  
  26. class Father extends GrandFather{  
  27.   
  28. }  
  29. class Child extends Father {  
  30.   
  31. }  
  32.   
  33. interface If<T>{  
  34.     void doSomething();  
  35. }  
  36.   
  37. class A  <T extends If<? super Father>> {  
  38. }  
  39.   
  40. class B <T extends If<Father>> {  
  41. }  
  42.   
  43. class C <T extends If<? extends Father>>{  
  44. }  

结果是:

这例子可以区分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>>()都报错
原文地址:https://www.cnblogs.com/justuntil/p/6896456.html