zoukankan      html  css  js  c++  java
  • JAVA总结--泛型

    泛型 :程序设计语言的一种特性;将类型参数化;

        特征:凡是涉及到强制类型转化的地方,使用泛型均会编译出现问题;泛型仅仅在编译时进行校验,使用泛型的对象,其本质的类型依然不变;

        ps:不存在泛型数组

    一、出现泛型的原因

     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 }

    位置//1编译阶段正常,而运行时会出现“java.lang.ClassCastException”异常

     在如上的编码过程中,我们发现主要存在两个问题:

    1.当我们将一个对象放入集合中,集合不会记住此对象的类型,当再次从集合中取出此对象时,改对象的编译类型变成了Object类型,但其运行时类型任然为其本身类型。

    2.因此,位置//1处取出集合元素时需要人为的强制类型转化到具体的目标类型,且很容易出现“java.lang.ClassCastException”异常。

    那么有没有什么办法可以使集合能够记住集合内元素各类型,且能够达到只要编译时不出现问题,运行时就不会出现“java.lang.ClassCastException”异常呢?答案就是使用泛型。

    二、泛型引入

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

    采用泛型写法后,在//1处想加入一个Integer类型的对象时会出现编译错误,通过List<String>,直接限定了list集合中只能含有String类型的元素,

    从而在//2处无须进行强制类型转换,因为此时,集合能够记住元素的类型信息,编译器已经能够确认它是String类型了。

    结合上面的泛型定义,我们知道在List<String>中,String是类型实参,也就是说,相应的List接口中肯定含有类型形参。

    且get()方法的返回结果也直接是此形参类型(也就是对应的传入的类型实参)。

    下面就来看看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 }
     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 }

    在List接口中采用泛型化定义之后,<E>中的E表示类型形参,可以接收具体的类型实参,并且此接口定义中,凡是出现E的地方均表示相同的接受自外部的类型实参。

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

    泛型可以分为泛型接口、泛型类和泛型方法;

    1、泛型类与泛型方法例子:

     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等形式的参数常用于表示泛型形参,由于接收来自外部使用时候传入的类型实参。

    2、传入不同类型,其对象实例的类型未发生变化

     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 }

    在使用泛型类时,虽然传入了不同的泛型实参,但并没有真正意义上生成不同的类型,我们仅仅在逻辑上可以理解成多个不同的泛型类型;

    在编译过程中,对于正确检验泛型结果后,会将泛型的相关信息擦出,也就是说,成功编译过后的class文件中是不包含任何泛型信息的。泛型信息不会进入到运行时阶段。

    即,泛型类型在逻辑上看以看成是多个不同的类型,实际上都是相同的基本类型;

    四、通配符的出现

    1、Box<Number>和Box<Integer>实际上都是Box类型,但是,相互之间并不是父子关系;

     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 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 }

    显然//1和//2处肯定会出现错误提示的。

    假设Box<Number>在逻辑上可以视为Box<Integer>的父类,那么//1和//2处将不会有错误提示了,那么问题就出来了,通过getData()方法取出数据时到底是什么类型呢?Integer? Float? 还是Number?

    且由于在编程过程中的顺序不可控性,导致在必要的时候必须要进行类型判断,且进行强制类型转换。

    这种问题的解决方式就是类型通配符

    2、类型通配符

     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 }
     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>形式,其含义与类型通配符上限正好相反;

  • 相关阅读:
    【HDU1724】Ellipse-自适应Simpson积分法
    【HDU1724】Ellipse-自适应Simpson积分法
    【51Nod1227】平均最小公倍数-杜教筛
    【51Nod1227】平均最小公倍数-杜教筛
    【HDU5628】Clarke and math-狄利克雷卷积+快速幂
    【HDU5628】Clarke and math-狄利克雷卷积+快速幂
    deleted
    deleted
    deleted
    deleted
  • 原文地址:https://www.cnblogs.com/huasky/p/8116899.html
Copyright © 2011-2022 走看看