Java_泛型

转自博客HappyCorn https://www.cnblogs.com/lwbqqyumidi/p/3837629.html

什么是泛型?

泛型,即“参数化类型”。一提到参数,最熟悉的就是定义方法时有形参,然后调用方法时传递实参。那么参数化类型怎么理解呢?顾名思义,就是将类型由原来的具体类型参数化,类似于方法中的变量参数,此时类型也定义成参数形式(可称为类型形参),然后在使用/调用时传入具体的类型(类型实参)。

一个栗子:

public class Generics {
 public static void main(String[] args) {
  List<String> list = new ArrayList<String>();
  list.add("Messi");
  list.add("Suarez");
  //list.add(100);  //1、提示编译错误
  
  for (int i = 0; i < list.size(); i++) {
   String name=list.get(i);  //2、
   System.out.println("the name is "+name);
  }
 }
}

采用泛型写法后,在//1处想加一个Integer类型的对象时会出现编译错误,通过List<String>,直接限定了list集合中只能含有String类型的元素,从而在//2处就无需进行强制类型转换,因为此时,集合能够记住元素的类型信息,编译器已经能够确认它是String类型了。

综合上面的泛型定义,我们知道在List<String>中,String是类型实参,也就是说,相应的List接口中肯定含有类型形参。且get()方法的返回结果也直接是此形参类型(也就是对应的传入的类型形参)。下面就来看看List接口的具体定义。

public interface List<E> extends Collection<E> {

    int size();

    boolean isEmpty();

    boolean contains(Object o);

    Iterator<E> iterator();

    Object[] toArray();

    <T> T[] toArray(T[] a);

    boolean add(E e);

    boolean remove(Object o);

    boolean containsAll(Collection<?> c);

    boolean addAll(Collection<? extends E> c);

    boolean addAll(int index, Collection<? extends E> c);

    boolean removeAll(Collection<?> c);

    boolean retainAll(Collection<?> c);

    void clear();

    boolean equals(Object o);

    int hashCode();

    E get(int index);

    E set(int index, E element);

    void add(int index, E element);

    E remove(int index);

    int indexOf(Object o);

    int lastIndexOf(Object o);

    ListIterator<E> listIterator();

    ListIterator<E> listIterator(int index);

    List<E> subList(int fromIndex, int toIndex);
}

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

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

public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable { public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
} public E get(int index) {
rangeCheck(index);
checkForComodification();
return ArrayList.this.elementData(offset + index);
} //...省略掉其他具体的定义过程 }

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

从上面的内容中,大家已经明白了泛型的具体操作过程。也知道了接口、类和方法也都可以使用泛型去定义,以及相应的使用。是的,在具体使用时,可以分为泛型接口,泛型类和泛型方法。

自定义泛型接口、泛型类和泛型方法与上述java源码中的List、ArrayList类似。如下,我们看一个最简单的泛型类和方法定义。

public class GenericsTest {
public static void main(String[] args) {
Box<String> name = new Box<String>("iron");
System.out.println("the name is "+name.getData());
}
} class Box<T>{
private T data; public Box(){} public Box(T data){
this.data = data;
} public T getData(){
return data;
}
}

在泛型接口、泛型类和泛型方法的定义过程中,我们常见的如T、E、K、V等形式的参数常用于表示泛型形参,用于接收来自外部使用时候传入的类型实参。那么对于不同传入的类型实参,生成的相应对象实例的类型是不是一样的呢?

public class GenericsTest {
public static void main(String[] args) {
Box<String> name = new Box<String>("iron");
Box<Integer> age = new Box<Integer>(38); System.out.println("name class: "+name.getClass()); //name class: class java_05.Box
System.out.println("age class: "+age.getClass()); //age class: class java_05.Box
System.out.println(name.getClass()==age.getClass()); //true System.out.println("the name is "+name.getData());
}
}

由此,我们发现,在使用泛型类时,虽然传入了不同的泛型实参,但并没有真正意义上生成不同的类型,传入不同泛型实参的泛型类在内存上只有一个,即还是原来的最基本的类型(本实例中为Box),当然,在逻辑上我们可以理解成多个不同的泛型类型。

究其原因,在于java中的泛型这一概念提出的目的,导致其只是作用于代码编译阶段,在编译过程中,对于正确校验泛型结果后,会将泛型的相关信息擦出,也就是说,成功编译过后的class文件中是不包含任何泛型信息的。泛型信息不会进入到运行时阶段。

对此总结成一句话:泛型类型在逻辑上可以看成是多个不同的类型,实际上都是相同的基本类型。

类型通配符:

接着上面的结论,我们知道,Box<Number> 和 Box<Integer>实际上都是Box类型,现在需要继续探讨一个问题,那么在逻辑上,类似于Box<Number>和Box<Integer>是否可以看成具有父子关系的泛型类型呢?

为了弄清这个问题,我们继续看下面这个例子:

public class GenericsTest {
public static void main(String[] args) {
Box<Number> name = new Box<Number>(99);
Box<Integer> age = new Box<Integer>(38); getData(name); //The method getData(Box<Number>) in
//the type GenericsTest is not applicable for the arguments (Box<Integer>)
//getData(age); //1、 } public static void getData(Box<Number> data) {
System.out.println("data :"+data.getData());
}
}

我们发现在代码//1、处出现了错误提示信息:The method getData(Box<Number>) in the type GenericsTest is not applicable for the arguments (Box<Integer>)。显然,通过提示信息,我们知道Box<Number>在逻辑上不能视为Box<Integer>的父类。那么,原因何在呢?

public class GenericsTest {
public static void main(String[] args) {
Box<Integer> a = new Box<Integer>(99);
Box<Number> b = a; //1、
Box<Float> f = new Box<Float>(3.14f);
b.setData(f); //2、
} public static void getData(Box<Number> data) {
System.out.println("data :"+data.getData());
}
} class Box<T>{
private T data; public Box(){} public Box(T data){
this.data = data;
} public T getData(){
return data;
} public void setData(){
this.data = data;
}
}

这个例子中。//1、和//2、处肯定会出现错误提示的。在此我们可以使用反证法进行说明。

假设Box<Number>在逻辑上可以视为Box<Integer>的父类,那么//1、//2、处将不会有错误提示,那么问题就出来了,通过getData()取出数据时到底是什么类型呢?Integer?Float?还是Number?且由于在编程过程中的顺序不可控性,导致在必要时候要进行类型判断,且进行强制类型转换。显然,这与泛型的理念相矛盾,因此,在逻辑上Box<Number>不能作为Box<Integer>的父类。

好,那我们回过头继续看“类型通配符”中的第一个例子,我们知道其具体错误提示的深层次原因了。那么如何解决呢?总不能再定义一个新的函数吧?这和java中的多态理念显然是违背的,因此,我们需要一个在逻辑上可以同时用来表示Box<Number>和Box<Integer> 父类的一个引用类型,由此 通配符应运而生。

类型通配符一般使用?代替具体的类型实参。注意,此处是类型实参,而不是类型形参。且Box<?>在逻辑上是Box<Number>,Box<Integer>...等所有Box<具体类型实参>的父类。由此,我们可以定义泛型方法,来完成此需求。

public class GenericsTest {
public static void main(String[] args) {
Box<String> name = new Box<String>("iron");
Box<Integer> age = new Box<Integer>(38);
Box<Number> num = new Box<Number>(315); getData(name);
getData(age);
getData(num); //getUpperNumberData(name); //1、
getUpperNumberData(age); //2、
getUpperNumberData(num); //3、
} public static void getData(Box<?> data){
System.out.println("data :"+data.getData());
} //Integer extends Number
public static void getUpperNumberData(Box<? extends Number> data){
System.out.println("data :"+data.getData());
}
}

此时,显然,在代码//1、处调用将出现错误提示,而//2、//3、处调用正常。

类型通配符上限通过形如Box<? extends Number>形式定义。相对应的,类型通配符下限形如Box<? super Number>形式,其含义与类型通配符上限正好相反。

话外篇:

一提到泛型,相信大家用到最多的就是在集合中,其实,在实际编程中,自己可以使用泛型去简化开发,且能很好的保证代码质量。并且还要注意一点的是,java中没有所谓的泛型数组一说。

对于泛型,最主要的还是需要理解其背后的思想和目的。

上一篇:python celery多worker、多队列、定时任务


下一篇:MySql截取DateTime字段的日期值