java 泛型初理解

泛型方法的定义:

  方法1:其中<T extends Comparable<T>>  是用来修饰 List<T>中的T的,意味T必须继承Comparable接口

1 public static <T extends Comparable<T>> void sort(List<T> list)

  方法2:其中<T extends Comparable<? super T>>  是用来修饰 List<T>中的T的,意味T或T的父类必须继承Comparable接口

1 public static <T extends Comparable<? super T>> void sort(List<T> list)

  定义测试对象(count最好给个随机数):

 1 public class A implements Comparable<A>
 2 {
 3      protected int count;
 4 
 5      @Override
 6      public int compareTo(A other)
 7      {
 8          return this.count- other.count;
 9      }
10 }
11 
12 public class B extends A
13 {
14 }

实例化测试对象,调用sort方法测试

 1 List<A> a= new ArrayList<A>();
 2 a.add(new A());
 3 a.add(new A());
 4 
 5 List<B> b= new ArrayList<B>();
 6 b.add(new B());
 7 b.add(new B());
 8 
 9 sort(a);
10 sort(b);//sort的泛型修饰符是<T extends Comparable<T>> 就会报错,因为B继承了A但本身没有实现Comparable接口,也不能实现,因为父类已经实现了。

 

  功能主要用来实现,扩展List的排序,比较等方法:

1 public class Date
2     implements java.io.Serializable, Cloneable, Comparable<Date>

  java.sql.Datejava.util.Date 的子类。

1 public class Date extends java.util.Date

 

  • java.util.Date 实现了 Comparable<java.util.Date>~,所以 ~java.sql.Date 也拥有了 Comparable<java.util.Date> 类型。
  • java.sql.Date 不能再 implements Comparable<java.sql.Date>
  • 如果你有一个 List<java.sql.Date> 并对它排序的话,只能传给拥有 <T extends Comparable<? super T>> 这种类型参数的方法。
posted @ 2016-04-15 15:09  何鸿涛  阅读(209)  评论(0)    收藏  举报