Java泛型是jdk1.5中引入的一个新特性,泛型提供了编译时的类型检测机制,该机制容许程序员在编译时检测到非法的类型。 泛型是Java中一个很是重要的知识点,在Java集合类框架中泛型被普遍应用。本文咱们将从零开始来看一下Java泛型的设计,将会涉及到通配符处理,以及让人苦恼的类型擦除。java
泛型类程序员
咱们首先定义一个简单的Box类:设计模式
public class Box { private String object; public void set(String object) { this.object = object; } public String get() { return object; } }
这是最多见的作法,这样作的一个坏处是Box里面如今只能装入String类型的元素,从此若是咱们须要装入Integer等其余类型的元素,还必需要另外重写一个Box,代码得不到复用,使用泛型能够很好的解决这个问题。数组
public class Box<T> { // T stands for "Type" private T t; public void set(T t) { this.t = t; } public T get() { return t; } }
这样咱们的Box
类即可以获得复用,咱们能够将T替换成任何咱们想要的类型:微信
Box<Integer> integerBox = new Box<Integer>(); Box<Double> doubleBox = new Box<Double>(); Box<String> stringBox = new Box<String>();
泛型方法app
看完了泛型类,接下来咱们来了解一下泛型方法。声明一个泛型方法很简单,只要在返回类型前面加上一个相似<K, V>
的形式就好了:框架
public class Util { public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) { return p1.getKey().equals(p2.getKey()) && p1.getValue().equals(p2.getValue()); } } public class Pair<K, V> { private K key; private V value; public Pair(K key, V value) { this.key = key; this.value = value; } public void setKey(K key) { this.key = key; } public void setValue(V value) { this.value = value; } public K getKey() { return key; } public V getValue() { return value; } }
咱们能够像下面这样去调用泛型方法:ui
Pair<Integer, String> p1 = new Pair<>(1, "apple"); Pair<Integer, String> p2 = new Pair<>(2, "pear"); boolean same = Util.<Integer, String>compare(p1, p2);
或者在Java1.7/1.8利用type inference,让Java自动推导出相应的类型参数:this
Pair<Integer, String> p1 = new Pair<>(1, "apple"); Pair<Integer, String> p2 = new Pair<>(2, "pear"); boolean same = Util.compare(p1, p2);
边界符spa
如今咱们要实现这样一个功能,查找一个泛型数组中大于某个特定元素的个数,咱们能够这样实现:
public static <T> int countGreaterThan(T[] anArray, T elem) { int count = 0; for (T e : anArray) if (e > elem) // compiler error ++count; return count; }
可是这样很明显是错误的,由于除了short, int, double, long, float, byte, char
等原始类型,其余的类并不必定能使用操做符>
,因此编译器报错,那怎么解决这个问题呢?答案是使用边界符。
public interface Comparable<T> { public int compareTo(T o); }
作一个相似于下面这样的声明,这样就等于告诉编译器类型参数T
表明的都是实现了Comparable
接口的类,这样等于告诉编译器它们都至少实现了compareTo
方法。
public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) { int count = 0; for (T e : anArray) if (e.compareTo(elem) > 0) ++count; return count; }
在了解通配符以前,咱们首先必需要澄清一个概念,仍是借用咱们上面定义的Box类,假设咱们添加一个这样的方法:
public void boxTest(Box<Number> n) { /* ... */ }
那么如今Box<Number> n
容许接受什么类型的参数?咱们是否可以传入Box<Integer>
或者Box<Double>
呢?答案是否认的,虽然Integer和Double是Number的子类,可是在泛型中Box<Integer>
或者Box<Double>
与Box<Number>
之间并无任何的关系。这一点很是重要,接下来咱们经过一个完整的例子来加深一下理解。
首先咱们先定义几个简单的类,下面咱们将用到它:
class Fruit {} class Apple extends Fruit {} class Orange extends Fruit {}
下面这个例子中,咱们建立了一个泛型类Reader
,而后在f1()
中当咱们尝试Fruit f = fruitReader.readExact(apples);
编译器会报错,由于List<Fruit>
与List<Apple>
之间并无任何的关系。
public class GenericReading { static List<Apple> apples = Arrays.asList(new Apple()); static List<Fruit> fruit = Arrays.asList(new Fruit()); static class Reader<T> { T readExact(List<T> list) { return list.get(0); } } static void f1() { Reader<Fruit> fruitReader = new Reader<Fruit>(); // Errors: List<Fruit> cannot be applied to List<Apple>. // Fruit f = fruitReader.readExact(apples); } public static void main(String[] args) { f1(); } }
可是按照咱们一般的思惟习惯,Apple和Fruit之间确定是存在联系,然而编译器却没法识别,那怎么在泛型代码中解决这个问题呢?咱们能够经过使用通配符来解决这个问题:
static class CovariantReader<T> { T readCovariant(List<? extends T> list) { return list.get(0); } } static void f2() { CovariantReader<Fruit> fruitReader = new CovariantReader<Fruit>(); Fruit f = fruitReader.readCovariant(fruit); Fruit a = fruitReader.readCovariant(apples); } public static void main(String[] args) { f2(); }
这样就至关与告诉编译器, fruitReader的readCovariant方法接受的参数只要是知足Fruit的子类就行(包括Fruit自身),这样子类和父类之间的关系也就关联上了。
PECS原则
上面咱们看到了相似<? extends T>
的用法,利用它咱们能够从list里面get元素,那么咱们可不能够往list里面add元素呢?咱们来尝试一下:
public class GenericsAndCovariance { public static void main(String[] args) { // Wildcards allow covariance: List<? extends Fruit> flist = new ArrayList<Apple>(); // Compile Error: can't add any type of object: // flist.add(new Apple()) // flist.add(new Orange()) // flist.add(new Fruit()) // flist.add(new Object()) flist.add(null); // Legal but uninteresting // We Know that it returns at least Fruit: Fruit f = flist.get(0); } }
答案是否认,Java编译器不容许咱们这样作,为何呢?对于这个问题咱们不妨从编译器的角度去考虑。由于List<? extends Fruit> flist
它自身能够有多种含义:
List<? extends Fruit> flist = new ArrayList<Fruit>(); List<? extends Fruit> flist = new ArrayList<Apple>(); List<? extends Fruit> flist = new ArrayList<Orange>();
new ArrayList<Orange>()
;new ArrayList<Apple>()
;因此对于实现了<? extends T>
的集合类只能将它视为Producer向外提供(get)元素,而不能做为Consumer来对外获取(add)元素。
若是咱们要add元素应该怎么作呢?可使用<? super T>
:
public class GenericWriting { static List<Apple> apples = new ArrayList<Apple>(); static List<Fruit> fruit = new ArrayList<Fruit>(); static <T> void writeExact(List<T> list, T item) { list.add(item); } static void f1() { writeExact(apples, new Apple()); writeExact(fruit, new Apple()); } static <T> void writeWithWildcard(List<? super T> list, T item) { list.add(item) } static void f2() { writeWithWildcard(apples, new Apple()); writeWithWildcard(fruit, new Apple()); } public static void main(String[] args) { f1(); f2(); } }
这样咱们能够往容器里面添加元素了,可是使用super的坏处是之后不能get容器里面的元素了,缘由很简单,咱们继续从编译器的角度考虑这个问题,对于List<? super Apple> list
,它能够有下面几种含义:
List<? super Apple> list = new ArrayList<Apple>(); List<? super Apple> list = new ArrayList<Fruit>(); List<? super Apple> list = new ArrayList<Object>();
当咱们尝试经过list来get一个Apple的时候,可能会get获得一个Fruit,这个Fruit能够是Orange等其余类型的Fruit。
根据上面的例子,咱们能够总结出一条规律,”Producer Extends, Consumer Super”:
? extends T
。? super T
。如何阅读过一些Java集合类的源码,能够发现一般咱们会将二者结合起来一块儿用,好比像下面这样:
public class Collections { public static <T> void copy(List<? super T> dest, List<? extends T> src) { for (int i=0; i<src.size(); i++) dest.set(i, src.get(i)); } }
Java泛型中最使人苦恼的地方或许就是类型擦除了,特别是对于有C++经验的程序员。类型擦除就是说Java泛型只能用于在编译期间的静态类型检查,而后编译器生成的代码会擦除相应的类型信息,这样到了运行期间实际上JVM根本就知道泛型所表明的具体类型。这样作的目的是由于Java泛型是1.5以后才被引入的,为了保持向下的兼容性,因此只能作类型擦除来兼容之前的非泛型代码。对于这一点,若是阅读Java集合框架的源码,能够发现有些类其实并不支持泛型。
说了这么多,那么泛型擦除究竟是什么意思呢?咱们先来看一下下面这个简单的例子:
public class Node<T> { private T data; private Node<T> next; public Node(T data, Node<T> next) } this.data = data; this.next = next; } public T getData() { return data; } // ... }
编译器作完相应的类型检查以后,实际上到了运行期间上面这段代码实际上将转换成:
public class Node { private Object data; private Node next; public Node(Object data, Node next) { this.data = data; this.next = next; } public Object getData() { return data; } // ... }
这意味着无论咱们声明Node<String>
仍是Node<Integer>
,到了运行期间,JVM通通视为Node<Object>
。有没有什么办法能够解决这个问题呢?这就须要咱们本身从新设置bounds了,将上面的代码修改为下面这样:
public class Node<T extends Comparable<T>> { private T data; private Node<T> next; public Node(T data, Node<T> next) { this.data = data; this.next = next; } public T getData() { return data; } // ... }
这样编译器就会将T
出现的地方替换成Comparable
而再也不是默认的Object
了:
public class Node { private Comparable data; private Node next; public Node(Comparable data, Node next) { this.data = data; this.next = next; } public Comparable getData() { return data; } // ... }
上面的概念或许仍是比较好理解,但其实泛型擦除带来的问题远远不止这些,接下来咱们系统地来看一下类型擦除所带来的一些问题,有些问题在C++的泛型中可能不会碰见,可是在Java中却须要格外当心。
问题一
在Java中不容许建立泛型数组,相似下面这样的作法编译器会报错:
List<Integer>[] arrayOfLists = new List<Integer>[2]; // compile-time error
为何编译器不支持上面这样的作法呢?继续使用逆向思惟,咱们站在编译器的角度来考虑这个问题。
咱们先来看一下下面这个例子:
Object[] strings = new String[2]; strings[0] = "hi"; // OK strings[1] = 100; // An ArrayStoreException is thrown.
对于上面这段代码仍是很好理解,字符串数组不能存放整型元素,并且这样的错误每每要等到代码运行的时候才能发现,编译器是没法识别的。接下来咱们再来看一下假设Java支持泛型数组的建立会出现什么后果:
Object[] stringLists = new List<String>[]; // compiler error, but pretend it's allowed stringLists[0] = new ArrayList<String>(); // OK // An ArrayStoreException should be thrown, but the runtime can't detect it. stringLists[1] = new ArrayList<Integer>();
假设咱们支持泛型数组的建立,因为运行时期类型信息已经被擦除,JVM实际上根本就不知道new ArrayList<String>()
和new ArrayList<Integer>()
的区别。相似这样的错误假如出现才实际的应用场景中,将很是难以察觉。
若是你对上面这一点还抱有怀疑的话,能够尝试运行下面这段代码:
public class ErasedTypeEquivalence { public static void main(String[] args) { Class c1 = new ArrayList<String>().getClass(); Class c2 = new ArrayList<Integer>().getClass(); System.out.println(c1 == c2); // true } }
问题二
继续复用咱们上面的Node
的类,对于泛型代码,Java编译器实际上还会偷偷帮咱们实现一个Bridge method。
public class Node<T> { public T data; public Node(T data) { this.data = data; } public void setData(T data) { System.out.println("Node.setData"); this.data = data; } } public class MyNode extends Node<Integer> { public MyNode(Integer data) { super(data); } public void setData(Integer data) { System.out.println("MyNode.setData"); super.setData(data); } }
看完上面的分析以后,你可能会认为在类型擦除后,编译器会将Node和MyNode变成下面这样:
public class Node { public Object data; public Node(Object data) { this.data = data; } public void setData(Object data) { System.out.println("Node.setData"); this.data = data; } } public class MyNode extends Node { public MyNode(Integer data) { super(data); } public void setData(Integer data) { System.out.println("MyNode.setData"); super.setData(data); } }
实际上不是这样的,咱们先来看一下下面这段代码,这段代码运行的时候会抛出ClassCastException
异常,提示String没法转换成Integer:
MyNode mn = new MyNode(5); Node n = mn; // A raw type - compiler throws an unchecked warning n.setData("Hello"); // Causes a ClassCastException to be thrown. // Integer x = mn.data;
若是按照咱们上面生成的代码,运行到第3行的时候不该该报错(注意我注释掉了第4行),由于MyNode中不存在setData(String data)
方法,因此只能调用父类Node的setData(Object data)
方法,既然这样上面的第3行代码不该该报错,由于String固然能够转换成Object了,那ClassCastException
究竟是怎么抛出的?
实际上Java编译器对上面代码自动还作了一个处理:
class MyNode extends Node { // Bridge method generated by the compiler public void setData(Object data) { setData((Integer) data); } public void setData(Integer data) { System.out.println("MyNode.setData"); super.setData(data); } // ... }
这也就是为何上面会报错的缘由了,setData((Integer) data);
的时候String没法转换成Integer。因此上面第2行编译器提示unchecked warning
的时候,咱们不能选择忽略,否则要等到运行期间才能发现异常。若是咱们一开始加上Node<Integer> n = mn
就行了,这样编译器就能够提早帮咱们发现错误。
问题三
正如咱们上面提到的,Java泛型很大程度上只能提供静态类型检查,而后类型的信息就会被擦除,因此像下面这样利用类型参数建立实例的作法编译器不会经过:
public static <E> void append(List<E> list) { E elem = new E(); // compile-time error list.add(elem); }
可是若是某些场景咱们想要须要利用类型参数建立实例,咱们应该怎么作呢?能够利用反射解决这个问题:
public static <E> void append(List<E> list, Class<E> cls) throws Exception { E elem = cls.newInstance(); // OK list.add(elem); }
咱们能够像下面这样调用:
List<String> ls = new ArrayList<>(); append(ls, String.class);
实际上对于上面这个问题,还能够采用Factory和Template两种设计模式解决,感兴趣的朋友不妨去看一下Thinking in Java中第15章中关于Creating instance of types(英文版第664页)的讲解,这里咱们就不深刻了。
问题四
咱们没法对泛型代码直接使用instanceof
关键字,由于Java编译器在生成代码的时候会擦除全部相关泛型的类型信息,正如咱们上面验证过的JVM在运行时期没法识别出ArrayList<Integer>
和ArrayList<String>
的之间的区别:
public static <E> void rtti(List<E> list) { if (list instanceof ArrayList<Integer>) { // compile-time error // ... } } => { ArrayList<Integer>, ArrayList<String>, LinkedList<Character>, ... }
和上面同样,咱们可使用通配符从新设置bounds来解决这个问题:
public static void rtti(List<?> list) { if (list instanceof ArrayList<?>) { // OK; instanceof requires a reifiable type // ... } }
我有一个微信公众号,常常会分享一些Java技术相关的干货。若是你喜欢个人分享,能够用微信搜索“Java团长”或者“javatuanzhang”关注。