• Java 泛型 介绍


      为什么需要泛型?

     1 public class GenericTest {
     2 
     3     public static void main(String[] args) {
     4         List list = new ArrayList();
     5         list.add("qqyumidi");
     6         list.add("corn");
     7         list.add(100);
     8 
     9         for (int i = 0; i < list.size(); i++) {
    10             String name = (String) list.get(i); // 1
    11             System.out.println("name:" + name);
    12         }
    13     }
    14 }

      定义一个List类型的集合,先增加2个String类型的值,再增加1个Integer类型的值。这是完全允许的,因为此时list默认的元素类型为Object类型。在之后的循环中,由于忘记了之前在list中也加入了Integer类型的值,出现上面1中的错误。编译时正常,而运行时出现java.lang.ClassCastException。因此,此类错误在编码过程中不易被发现。

      增加一个对象到集合中,集合不会记住此对象的类型。从集合中取出此对象时,该对象的编译时类型(表面类型)是Object类型,但其运行时类型(实际类型)是本身类型。因此,上面1处取出集合元素时需要人为地强制类型转换到具体的目标类型,容易出现java.lang.ClassCastException。

      使用泛型达到这一目的——使集合能够记住集合内元素类型,只要编译时不出现问题,运行时就不会出现java.lang.ClassCastException。

      什么是泛型?

      泛型指参数化类型。将原来的具体类型参数化,类似于方法中的形参,类型定义成了参数形式即类型形参,然后在使用时传入具体的类型即类型实参。

      使用泛型来修改上面的代码:

     1 public class GenericTest {
     2 
     3     public static void main(String[] args) {
     4         /*
     5         List list = new ArrayList();
     6         list.add("qqyumidi");
     7         list.add("corn");
     8         list.add(100);
     9         */
    10 
    11         List<String> list = new ArrayList<String>();
    12         list.add("qqyumidi");
    13         list.add("corn");
    14         //list.add(100);   // 1  提示编译错误
    15 
    16         for (int i = 0; i < list.size(); i++) {
    17             String name = list.get(i); // 2
    18             System.out.println("name:" + name);
    19         }
    20     }
    21 }

      采用泛型写法后,在上面1处增加1个Integer对象时会出现编译错误。List<String>中String是类型实参,直接限定了集合中只能含有String类型的元素,从而上面2处无需进行强制类型转换。也就是说,集合记住了元素的类型,编译器确认了它是String类型。

      List接口的定义:

     1 public interface List<E> extends Collection<E> {
     2 
     3     int size();
     4 
     5     boolean isEmpty();
     6 
     7     boolean contains(Object o);
     8 
     9     Iterator<E> iterator();
    10 
    11     Object[] toArray();
    12 
    13     <T> T[] toArray(T[] a);
    14 
    15     boolean add(E e);
    16 
    17     boolean remove(Object o);
    18 
    19     boolean containsAll(Collection<?> c);
    20 
    21     boolean addAll(Collection<? extends E> c);
    22 
    23     boolean addAll(int index, Collection<? extends E> c);
    24 
    25     boolean removeAll(Collection<?> c);
    26 
    27     boolean retainAll(Collection<?> c);
    28 
    29     void clear();
    30 
    31     boolean equals(Object o);
    32 
    33     int hashCode();
    34 
    35     E get(int index);
    36 
    37     E set(int index, E element);
    38 
    39     void add(int index, E element);
    40 
    41     E remove(int index);
    42 
    43     int indexOf(Object o);
    44 
    45     int lastIndexOf(Object o);
    46 
    47     ListIterator<E> listIterator();
    48 
    49     ListIterator<E> listIterator(int index);
    50 
    51     List<E> subList(int fromIndex, int toIndex);
    52 }

      List接口采用了泛型定义,<E>中的E表示类型形参,用于接收具体的类型实参。出现E的地方均表示接收外部相同的类型实参。

      作为List接口的实现类,ArrayList的定义形式:

     1 public class ArrayList<E> extends AbstractList<E> 
     2         implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
     3     
     4     public boolean add(E e) {
     5         ensureCapacityInternal(size + 1);  // Increments modCount!!
     6         elementData[size++] = e;
     7         return true;
     8     }
     9     
    10     public E get(int index) {
    11         rangeCheck(index);
    12         checkForComodification();
    13         return ArrayList.this.elementData(offset + index);
    14     }
    15     
    16     //...省略掉其他具体的定义过程
    17 
    18 }

      

      自定义泛型接口、泛型类和泛型方法

      泛型类和泛型方法定义实例:

     1 public class GenericTest {
     2 
     3     public static void main(String[] args) {
     4 
     5         Box<String> name = new Box<String>("corn");
     6         System.out.println("name:" + name.getData());
     7     }
     8 
     9 }
    10 
    11 class Box<T> {
    12 
    13     private T data;
    14 
    15     public Box() {
    16 
    17     }
    18 
    19     public Box(T data) {
    20         this.data = data;
    21     }
    22 
    23     public T getData() {
    24         return data;
    25     }
    26 
    27 }

      常见的如T、E、K、V等形式的参数通常表示类型形参,接收外部传入的类型实参。<T>表示泛型方法,T是方法的返回类型。

      对于传入的不同类型实参,相应生成的对象实例的类型是否一样?

     1 public class GenericTest {
     2 
     3     public static void main(String[] args) {
     4 
     5         Box<String> name = new Box<String>("corn");
     6         Box<Integer> age = new Box<Integer>(712);
     7 
     8         System.out.println("name class:" + name.getClass());      // com.qqyumidi.Box
     9         System.out.println("age class:" + age.getClass());        // com.qqyumidi.Box
    10         System.out.println(name.getClass() == age.getClass());    // true
    11 
    12     }
    13 
    14 }

      在使用泛型类时,虽然传入了不同的类型实参,但没有生成不同的类型。可以传入不同类型实参的泛型类在内存上只有一个,即原来的基本类型(本实例中为Box)。因为泛型只是作用于编译阶段,通过编译的class文件是不包含任何泛型信息的。

      类型通配符

      根据上面的实例,Box<Number>和Box<Integer>实际上都是Box类型。Box<Number>和Box<Integer>是否可以看成具有父子关系的泛型类型呢?

     1 public class GenericTest {
     2 
     3     public static void main(String[] args) {
     4 
     5         Box<Number> name = new Box<Number>(99);
     6         Box<Integer> age = new Box<Integer>(712);
     7 
     8         getData(name);
     9         
    10         //The method getData(Box<Number>) in the type GenericTest is 
    11         //not applicable for the arguments (Box<Integer>)
    12         getData(age);   // 1
    13 
    14     }
    15     
    16     public static void getData(Box<Number> data){
    17         System.out.println("data :" + data.getData());
    18     }
    19 
    20 }

      上面1处出现了错误提示信息:The method getData(Box<Number>) in the t ype GenericTest is not applicable for the arguments (Box<Integer>)。Box<Number>不能视为Box<Integer>的父类。

      为什么?

     1 public class GenericTest {
     2 
     3     public static void main(String[] args) {
     4 
     5         Box<Integer> a = new Box<Integer>(712);
     6         Box<Number> b = a;  // 1
     7         Box<Float> f = new Box<Float>(3.14f);
     8         b.setData(f);        // 2
     9 
    10     }
    11 
    12     public static void getData(Box<Number> data) {
    13         System.out.println("data :" + data.getData());
    14     }
    15 
    16 }
    17 
    18 class Box<T> {
    19 
    20     private T data;
    21 
    22     public Box() {
    23 
    24     }
    25 
    26     public Box(T data) {
    27         setData(data);
    28     }
    29 
    30     public T getData() {
    31         return data;
    32     }
    33 
    34     public void setData(T data) {
    35         this.data = data;
    36     }
    37 
    38 }

      上面1处和2处肯定会出现错误提示。使用反证法来说明:

      假设Box<Number>可以视为Box<Integer>的父类,上面1处和2处将不会有错误提示。通过getData方法取出的数据到底是什么类型?Integer? Float? 还是Number?由于编程过程的顺序不可控性,在必要的时候判断类型,进行强制类型转换。这与泛型的理念矛盾。因此,Box<Number>不能视为Box<Integer>的父类。

      类型通配符用来表示Box<Integer>和Box<Number>的父类的引用类型。

      类型通配符使用?代替具体的类型实参。Box<?>是Box<Integer>和Box<Number>等所有Box<类型实参>的父类。

      实例如下:

     1 public class GenericTest {
     2 
     3     public static void main(String[] args) {
     4 
     5         Box<String> name = new Box<String>("corn");
     6         Box<Integer> age = new Box<Integer>(712);
     7         Box<Number> number = new Box<Number>(314);
     8 
     9         getData(name);
    10         getData(age);
    11         getData(number);
    12     }
    13 
    14     public static void getData(Box<?> data) {
    15         System.out.println("data :" + data.getData());
    16     }
    17 
    18 }

      限制类型实参只能是Number类及其子类,需要用到类型通配符上限:

     1 public class GenericTest {
     2 
     3     public static void main(String[] args) {
     4 
     5         Box<String> name = new Box<String>("corn");
     6         Box<Integer> age = new Box<Integer>(712);
     7         Box<Number> number = new Box<Number>(314);
     8 
     9         getData(name);
    10         getData(age);
    11         getData(number);
    12         
    13         //getUpperNumberData(name); // 1
    14         getUpperNumberData(age);    // 2
    15         getUpperNumberData(number); // 3
    16     }
    17 
    18     public static void getData(Box<?> data) {
    19         System.out.println("data :" + data.getData());
    20     }
    21     
    22     public static void getUpperNumberData(Box<? extends Number> data){
    23         System.out.println("data :" + data.getData());
    24     }
    25 
    26 }

      上面1处调用会出现错误,而上面2处和3处调用正常。

      总之,类型通配符上限为Box<? extends Number>形式,类型通配符下限为Box<? super Number>形式,其含义与类型通配符上限相反。

      注意:Java中没有泛型数组。

      参考资料

      Java总结篇系列:Java泛型

      <T>和T的区别

  • 相关阅读:
    贪婪算法、递归计算、动态规划背包问题
    递归、动态规划计算斐波那契数列
    用于确定两个字符串最长公共子串的函数
    快速排序算法
    顺序、二分查找文本数据
    MyBatis面试题
    Spring面试题
    SpringMvc面试题
    jsp和servlet面试
    EJB的理解
  • 原文地址:https://www.cnblogs.com/WJQ2017/p/7676907.html
Copyright © 2020-2023  润新知