引言

泛型是Java中一个非常重要的知识点,在Java集合类框架中泛型被广泛应用。本文我们将从零开始来看一下Java泛型的设计,将会涉及到通配符处理,以及让人苦恼的类型擦除。

泛型基础

泛型类

我们首先定义一个简单的Box类:

  1. public class Box {

  2.  

  3. private String object;

  4.  

  5. public void set(String object) { this.object = object; }

  6.  

  7. public String get() { return object; }

  8.  

  9. }

这是最常见的做法,这样做的一个坏处是Box里面现在只能装入String类型的元素,今后如果我们需要装入Integer等其他类型的元素,还必须要另外重写一个Box,代码得不到复用,使用泛型可以很好的解决这个问题。

  1. public class Box<T> {

  2.  

  3. private T t;

  4.  

  5. public void set(T t) { this.t = t; }

  6.  

  7. public T get() { return t; }

  8.  

  9. }

这样我们的Box类便可以得到复用,我们可以将T替换成任何我们想要的类型:

  1. Box<Integer> integerBox = new Box<Integer>();

  2.  

  3. Box<Double> doubleBox = new Box<Double>();

  4.  

  5. Box<String> stringBox = new Box<String>();

泛型方法

看完了泛型类,接下来我们来了解一下泛型方法。声明一个泛型方法很简单,只要在返回类型前面加上一个类似<k, v="">的形式就行了:</k,>

  1. public class Util {

  2.  

  3. public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) {

  4.  

  5. return p1.getKey().equals(p2.getKey()) &&

  6.  

  7. p1.getValue().equals(p2.getValue());

  8.  

  9. }

  10.  

  11. }

  12.  

  13. public class Pair<K, V> {

  14.  

  15. private K key;

  16.  

  17. private V value;

  18.  

  19. public Pair(K key, V value) {

  20.  

  21. this.key = key;

  22.  

  23. this.value = value;

  24.  

  25. }

  26.  

  27. public void setKey(K key) { this.key = key; }

  28.  

  29. public void setValue(V value) { this.value = value; }

  30.  

  31. public K getKey() { return key; }

  32.  

  33. public V getValue() { return value; }

  34.  

  35. }

我们可以像下面这样去调用泛型方法:

  1. Pair<Integer, String> p1 = new Pair<>(1, "apple");

  2.  

  3. Pair<Integer, String> p2 = new Pair<>(2, "pear");

  4.  

  5. boolean same = Util.<Integer, String>compare(p1, p2);

或者在Java1.7/1.8利用type inference,让Java自动推导出相应的类型参数:

  1. Pair<Integer, String> p1 = new Pair<>(1, "apple");

  2.  

  3. Pair<Integer, String> p2 = new Pair<>(2, "pear");

  4.  

  5. boolean same = Util.compare(p1, p2);

边界符

现在我们要实现这样一个功能,查找一个泛型数组中大于某个特定元素的个数,我们可以这样实现:

  1. public static <T> int countGreaterThan(T[] anArray, T elem) {

  2.  

  3. int count = 0;

  4.  

  5. for (T e : anArray)

  6.  

  7. if (e > elem)

  8.  

  9. ++count;

  10.  

  11. return count;

  12.  

  13. }

但是这样很明显是错误的,因为除了short, int, double, long, float, byte, char等原始类型,其他的类并不一定能使用操作符>,所以编译器报错,那怎么解决这个问题呢?答案是使用边界符。

  1. public interface Comparable<T> {

  2.  

  3. public int compareTo(T o);

  4.  

  5. }

做一个类似于下面这样的声明,这样就等于告诉编译器类型参数T代表的都是实现了Comparable接口的类,这样等于告诉编译器它们都至少实现了compareTo方法。

  1. public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {

  2.  

  3. int count = 0;

  4.  

  5. for (T e : anArray)

  6.  

  7. if (e.compareTo(elem) > 0)

  8.  

  9. ++count;

  10.  

  11. return count;

  12.  

  13. }

通配符

在了解通配符之前,我们首先必须要澄清一个概念,还是借用我们上面定义的Box类,假设我们添加一个这样的方法:

  1. public void boxTest(Box<Number> n) { }

那么现在Box n允许接受什么类型的参数?我们是否能够传入Box或者Box呢?答案是否定的,虽然Integer和Double是Number的子类,但是在泛型中Box或者Box与Box之间并没有任何的关系。这一点非常重要,接下来我们通过一个完整的例子来加深一下理解。

首先我们先定义几个简单的类,下面我们将用到它:

  1. class Fruit {}

  2.  

  3. public class GenericReading {

  4.  

  5. static List<Apple> apples = Arrays.asList(new Apple());

  6.  

  7. static List<Fruit> fruit = Arrays.asList(new Fruit());

  8.  

  9. static class Reader<T> {

  10.  

  11. T readExact(List<T> list) {

  12.  

  13. return list.get(0);

  14.  

  15. }

  16.  

  17. }

  18.  

  19. static void f1() {

  20.  

  21. static class CovariantReader<T> {

  22.  

  23. T readCovariant(List<? extends T> list) {

  24.  

  25. return list.get(0);

  26.  

  27. }

  28.  

  29. }

  30.  

  31. static void f2() {

  32.  

  33. CovariantReader<Fruit> fruitReader = new CovariantReader<Fruit>();

  34.  

  35. Fruit f = fruitReader.readCovariant(fruit);

  36.  

  37. Fruit a = fruitReader.readCovariant(apples);

  38.  

  39. }

  40.  

  41. public static void main(String[] args) {

  42.  

  43. f2();

  44.  

  45. }

这样就相当与告诉编译器, fruitReader的readCovariant方法接受的参数只要是满足Fruit的子类就行(包括Fruit自身),这样子类和父类之间的关系也就关联上了。

PECS原则

上面我们看到了类似的用法,利用它我们可以从list里面get元素,那么我们可不可以往list里面add元素呢?我们来尝试一下:

  1. public class GenericsAndCovariance {

  2.  

  3. public static void main(String[] args) {

  4.  

  5. List<? extends Fruit> flist = new ArrayList<Apple>();

  6.  

  7. flist.add(null);

  8.  

  9. Fruit f = flist.get(0);

  10.  

  11. }

  12.  

  13. }

答案是否定,Java编译器不允许我们这样做,为什么呢?对于这个问题我们不妨从编译器的角度去考虑。因为Listflist它自身可以有多种含义:

  1. List<? extends Fruit> flist = new ArrayList<Fruit>();

  2.  

  3. List<? extends Fruit> flist = new ArrayList<Apple>();

  4.  

  5. List<? extends Fruit> flist = new ArrayList<Orange>();

当我们尝试add一个Apple的时候,flist可能指向new ArrayList();

当我们尝试add一个Orange的时候,flist可能指向new ArrayList();

当我们尝试add一个Fruit的时候,这个Fruit可以是任何类型的Fruit,而flist可能只想某种特定类型的Fruit,编译器无法识别所以会报错。

所以对于实现了的集合类只能将它视为Producer向外提供(get)元素,而不能作为Consumer来对外获取(add)元素。

如果我们要add元素应该怎么做呢?可以使用:

  1. public class GenericWriting {

  2.  

  3. static List<Apple> apples = new ArrayList<Apple>();

  4.  

  5. static List<Fruit> fruit = new ArrayList<Fruit>();

  6.  

  7. static <T> void writeExact(List<T> list, T item) {

  8.  

  9. list.add(item);

  10.  

  11. }

  12.  

  13. static void f1() {

  14.  

  15. writeExact(apples, new Apple());

  16.  

  17. writeExact(fruit, new Apple());

  18.  

  19. }

  20.  

  21. static <T> void writeWithWildcard(List<? super T> list, T item) {

  22.  

  23. list.add(item)

  24.  

  25. }

  26.  

  27. static void f2() {

  28.  

  29. writeWithWildcard(apples, new Apple());

  30.  

  31. writeWithWildcard(fruit, new Apple());

  32.  

  33. }

  34.  

  35. public static void main(String[] args) {

  36.  

  37. f1(); f2();

  38.  

  39. }

  40.  

  41. }

这样我们可以往容器里面添加元素了,但是使用super的坏处是以后不能get容器里面的元素了,原因很简单,我们继续从编译器的角度考虑这个问题,对于List list,它可以有下面几种含义:

  1. List<? super Apple> list = new ArrayList<Apple>();

  2.  

  3. List<? super Apple> list = new ArrayList<Fruit>();

  4.  

  5. List<? super Apple> list = new ArrayList<Object>();

当我们尝试通过list来get一个Apple的时候,可能会get得到一个Fruit,这个Fruit可以是Orange等其他类型的Fruit。

根据上面的例子,我们可以总结出一条规律,”Producer Extends, Consumer Super”:

“Producer Extends” – 如果你需要一个只读List,用它来produce T,那么使用? extends T。

“Consumer Super” – 如果你需要一个只写List,用它来consume T,那么使用? super T。

如果需要同时读取以及写入,那么我们就不能使用通配符了。

如何阅读过一些Java集合类的源码,可以发现通常我们会将两者结合起来一起用,比如像下面这样:

  1. public class Collections {

  2.  

  3. public static <T> void copy(List<? super T> dest, List<? extends T> src) {

  4.  

  5. for (int i=0; i<src.size(); i++)

  6.  

  7. dest.set(i, src.get(i));

  8.  

  9. }

  10.  

  11. }

类型擦除

Java泛型中最令人苦恼的地方或许就是类型擦除了,特别是对于有C++经验的程序员。类型擦除就是说Java泛型只能用于在编译期间的静态类型检查,然后编译器生成的代码会擦除相应的类型信息,这样到了运行期间实际上JVM根本就知道泛型所代表的具体类型。这样做的目的是因为Java泛型是1.5之后才被引入的,为了保持向下的兼容性,所以只能做类型擦除来兼容以前的非泛型代码。对于这一点,如果阅读Java集合框架的源码,可以发现有些类其实并不支持泛型。

说了这么多,那么泛型擦除到底是什么意思呢?我们先来看一下下面这个简单的例子:

  1. public class Node<T> {

  2.  

  3. private T data;

  4.  

  5. private Node<T> next;

  6.  

  7. public Node(T data, Node<T> next) {

  8.  

  9. this.data = data;

  10.  

  11. this.next = next;

  12.  

  13. }

  14.  

  15. public T getData() { return data; }

  16.  

  17. }

编译器做完相应的类型检查之后,实际上到了运行期间上面这段代码实际上将转换成:

  1. public class Node {

  2.  

  3. private Object data;

  4.  

  5. private Node next;

  6.  

  7. public Node(Object data, Node next) {

  8.  

  9. this.data = data;

  10.  

  11. this.next = next;

  12.  

  13. }

  14.  

  15. public Object getData() { return data; }

  16.  

  17. }

这意味着不管我们声明Node还是Node,到了运行期间,JVM统统视为Node。有没有什么办法可以解决这个问题呢?这就需要我们自己重新设置bounds了,将上面的代码修改成下面这样:

 

  1. public class Node<T extends Comparable<T>> {

  2.  

  3. private T data;

  4.  

  5. private Node<T> next;

  6.  

  7. public Node(T data, Node<T> next) {

  8.  

  9. this.data = data;

  10.  

  11. this.next = next;

  12.  

  13. }

  14.  

  15. public T getData() { return data; }

  16.  

  17. }

这样编译器就会将T出现的地方替换成Comparable而不再是默认的Object了:

  1. public class Node {

  2.  

  3. private Comparable data;

  4.  

  5. private Node next;

  6.  

  7. public Node(Comparable data, Node next) {

  8.  

  9. this.data = data;

  10.  

  11. this.next = next;

  12.  

  13. }

  14.  

  15. public Comparable getData() { return data; }

  16.  

  17. }

上面的概念或许还是比较好理解,但其实泛型擦除带来的问题远远不止这些,接下来我们系统地来看一下类型擦除所带来的一些问题,有些问题在C++的泛型中可能不会遇见,但是在Java中却需要格外小心。

问题一

在Java中不允许创建泛型数组,类似下面这样的做法编译器会报错:

  1. List<Integer>[] arrayOfLists = new List<Integer>[2];

为什么编译器不支持上面这样的做法呢?继续使用逆向思维,我们站在编译器的角度来考虑这个问题。

我们先来看一下下面这个例子:

  1. Object[] strings = new String[2];

  2.  

  3. strings[0] = "hi";

  4.  

  5. strings[1] = 100;

对于上面这段代码还是很好理解,字符串数组不能存放整型元素,而且这样的错误往往要等到代码运行的时候才能发现,编译器是无法识别的。接下来我们再来看一下假设Java支持泛型数组的创建会出现什么后果:

  1. Object[] stringLists = new List<String>[];

  2.  

  3. stringLists[0] = new ArrayList<String>();

  4.  

  5. stringLists[1] = new ArrayList<Integer>();

假设我们支持泛型数组的创建,由于运行时期类型信息已经被擦除,JVM实际上根本就不知道new ArrayList()和new ArrayList()的区别。类似这样的错误假如出现才实际的应用场景中,将非常难以察觉。

如果你对上面这一点还抱有怀疑的话,可以尝试运行下面这段代码:

  1. public class ErasedTypeEquivalence {

  2.  

  3. public static void main(String[] args) {

  4.  

  5. Class c1 = new ArrayList<String>().getClass();

  6.  

  7. Class c2 = new ArrayList<Integer>().getClass();

  8.  

  9. System.out.println(c1 == c2);

  10.  

  11. }

  12.  

  13. }

问题二

继续复用我们上面的Node的类,对于泛型代码,Java编译器实际上还会偷偷帮我们实现一个Bridge method。

  1. public class Node<T> {

  2.  

  3. public T data;

  4.  

  5. public Node(T data) { this.data = data; }

  6.  

  7. public void setData(T data) {

  8.  

  9. System.out.println("Node.setData");

  10.  

  11. this.data = data;

  12.  

  13. }

  14.  

  15. }

  16.  

  17. public class MyNode extends Node<Integer> {

  18.  

  19. public MyNode(Integer data) { super(data); }

  20.  

  21. public void setData(Integer data) {

  22.  

  23. System.out.println("MyNode.setData");

  24.  

  25. super.setData(data);

  26.  

  27. }

  28.  

  29. }

看完上面的分析之后,你可能会认为在类型擦除后,编译器会将Node和MyNode变成下面这样:

  1. public class Node {

  2.  

  3. public Object data;

  4.  

  5. public Node(Object data) { this.data = data; }

  6.  

  7. public void setData(Object data) {

  8.  

  9. System.out.println("Node.setData");

  10.  

  11. this.data = data;

  12.  

  13. }

  14.  

  15. }

  16.  

  17. public class MyNode extends Node {

  18.  

  19. public MyNode(Integer data) { super(data); }

  20.  

  21. public void setData(Integer data) {

  22.  

  23. System.out.println("MyNode.setData");

  24.  

  25. super.setData(data);

  26.  

  27. }

  28.  

  29. }

实际上不是这样的,我们先来看一下下面这段代码,这段代码运行的时候会抛出ClassCastException异常,提示String无法转换成Integer:

  1. MyNode mn = new MyNode(5);

  2.  

  3. Node n = mn;

  4.  

  5. n.setData("Hello");

如果按照我们上面生成的代码,运行到第3行的时候不应该报错(注意我注释掉了第4行),因为MyNode中不存在setData(String data)方法,所以只能调用父类Node的setData(Object data)方法,既然这样上面的第3行代码不应该报错,因为String当然可以转换成Object了,那ClassCastException到底是怎么抛出的?

实际上Java编译器对上面代码自动还做了一个处理:

  1. class MyNode extends Node {

  2.  

  3. public void setData(Object data) {

  4.  

  5. setData((Integer) data);

  6.  

  7. }

  8.  

  9. public void setData(Integer data) {

  10.  

  11. System.out.println("MyNode.setData");

  12.  

  13. super.setData(data);

  14.  

  15. }

  16.  

  17. }

这也就是为什么上面会报错的原因了,setData((Integer) data);的时候String无法转换成Integer。所以上面第2行编译器提示unchecked warning的时候,我们不能选择忽略,不然要等到运行期间才能发现异常。如果我们一开始加上Node n = mn就好了,这样编译器就可以提前帮我们发现错误。

问题三

正如我们上面提到的,Java泛型很大程度上只能提供静态类型检查,然后类型的信息就会被擦除,所以像下面这样利用类型参数创建实例的做法编译器不会通过:

  1. public static <E> void append(List<E> list) {

  2.  

  3. E elem = new E();

  4.  

  5. list.add(elem);

  6.  

  7. }

但是如果某些场景我们想要需要利用类型参数创建实例,我们应该怎么做呢?可以利用反射解决这个问题:

  1. public static <E> void append(List<E> list, Class<E> cls) throws Exception {

  2.  

  3. E elem = cls.newInstance();

  4.  

  5. list.add(elem);

  6.  

  7. }

我们可以像下面这样调用:

  1. List<String> ls = new ArrayList<>();

  2.  

  3. append(ls, String.class);

实际上对于上面这个问题,还可以采用Factory和Template两种设计模式解决,感兴趣的朋友不妨去看一下Thinking in Java中第15章中关于Creating instance of types(英文版第664页)的讲解,这里我们就不深入了。

问题四

我们无法对泛型代码直接使用instanceof关键字,因为Java编译器在生成代码的时候会擦除所有相关泛型的类型信息,正如我们上面验证过的JVM在运行时期无法识别出ArrayList和ArrayList的之间的区别:

  1. public static <E> void rtti(List<E> list) {

  2.  

  3. if (list instanceof ArrayList<Integer>) {

  4.  

  5. }

  6.  

  7. }

  8.  

  9. => { ArrayList<Integer>, ArrayList<String>, LinkedList<Character>, ... }

和上面一样,我们可以使用通配符重新设置bounds来解决这个问题:

  1. public static void rtti(List<?> list) {

  2.  

  3. if (list instanceof ArrayList<?>) {

  4.  

  5. }

  6.  

  7. }

工厂模式

接下来我们利用泛型来简单的实现一下工厂模式,首先我们先声明一个接口Factory:

  1. package typeinfo.factory;

  2.  

  3. public interface Factory<T> {

  4.  

  5. T create();

  6.  

  7. }

接下来我们来创建几个实体类FuelFilter和AirFilter以及FanBelt和GeneratorBelt。

  1. class Filter extends Part {}

  2.  

  3. class FuelFilter extends Filter {

  4.  

  5. public static class Factory implements typeinfo.factory.Factory<FuelFilter> {

  6.  

  7. public FuelFilter create() {

  8.  

  9. return new FuelFilter();

  10.  

  11. }

  12.  

  13. }

  14.  

  15. }

  16.  

  17. class AirFilter extends Filter {

  18.  

  19. public static class Factory implements typeinfo.factory.Factory<AirFilter> {

  20.  

  21. public AirFilter create() {

  22.  

  23. return new AirFilter();

  24.  

  25. }

  26.  

  27. }

  28.  

  29. }

  1. class Belt extends Part {}

  2.  

  3. class FanBelt extends Belt {

  4.  

  5. public static class Factory implements typeinfo.factory.Factory<FanBelt> {

  6.  

  7. public FanBelt create() {

  8.  

  9. return new FanBelt();

  10.  

  11. }

  12.  

  13. }

  14.  

  15. }

  16.  

  17. class GeneratorBelt extends Belt {

  18.  

  19. public static class Factory implements typeinfo.factory.Factory<GeneratorBelt> {

  20.  

  21. public GeneratorBelt create() {

  22.  

  23. return new GeneratorBelt();

  24.  

  25. }

  26.  

  27. }

  28.  

  29. }

Part类的实现如下,注意我们上面的实体类都是Part类的间接子类。在Part类我们注册了我们上面的声明的实体类。所以以后我们如果要创建相关的实体类的话,只需要在调用Part类的相关方法了。这么做的一个好处就是如果的业务中出现了CabinAirFilter或者PowerSteeringBelt的话,我们不需要修改太多的代码,只需要在Part类中将它们注册即可。

  1. class Part {

  2.  

  3. static List<Factory<? extends Part>> partFactories =

  4.  

  5. new ArrayList<Factory<? extends Part>>();

  6.  

  7. static {

  8.  

  9. partFactories.add(new FuelFilter.Factory());

  10.  

  11. partFactories.add(new AirFilter.Factory());

  12.  

  13. partFactories.add(new FanBelt.Factory());

  14.  

  15. partFactories.add(new PowerSteeringBelt.Factory());

  16.  

  17. }

  18.  

  19. private static Random rand = new Random(47);

  20.  

  21. public static Part createRandom() {

  22.  

  23. int n = rand.nextInt(partFactories.size());

  24.  

  25. return partFactories.get(n).create();

  26.  

  27. }

  28.  

  29. public String toString() {

  30.  

  31. return getClass().getSimpleName();

  32.  

  33. }

  34.  

  35. }

最后我们来测试一下:

  1. public class RegisteredFactories {

  2.  

  3. public static void main(String[] args) {

  4.  

  5. for (int i = 0; i < 10; i++) {

  6.  

  7. System.out.println(Part.createRandom());

  8.  

  9. }

  10.  

  11. }

  12.  

  13. }

References
  • ORACLE-DOCUMENTATION

  • THINKING IN JAVA

  • EFFECTIVE JAVA

https://mp.weixin.qq.com/s/zcJ0g0Y2tXpug59544vVWw