引言
泛型是Java中一个非常重要的知识点,在Java集合类框架中泛型被广泛应用。 Java中泛型的引入主要是为了解决两个方面的问题:1.集合类型元素在运行期出现类型装换异常,增加编译时类型的检查,2. 解决重复代码的编写,能够复用算法。
泛型基础
泛型类
我们首先定义一个简单的Box类:
1
2
3
4
5
|
public class Box {
private String boxname;
public void set(String boxname) { this.boxname = boxname; }
public String get() { return boxname; }
}
|
这是最常见的做法,这样做的一个坏处是Box里面现在只能装入String类型的元素,今后如果我们需要装入Integer等其他类型的元素,还必须要另外重写一个Box,代码得不到复用,使用泛型可以很好的解决这个问题。
1
2
3
4
5
6
|
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替换成任何我们想要的类型:
1
2
3
|
Box<Integer> integerBox = new Box<Integer>();
Box<Double> doubleBox = new Box<Double>();
Box<String> stringBox = new Box<String>();
|
泛型方法
看完了泛型类,接下来我们来了解一下泛型方法。声明一个泛型方法很简单,只要在返回类型前面加上一个类似<K, V>
的形式就行了:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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; }
}
|
我们可以像下面这样去调用泛型方法:
1
2
3
|
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自动推导出相应的类型参数:
1
2
3
|
Pair<Integer, String> p1 = new Pair<>( 1 , "apple" );
Pair<Integer, String> p2 = new Pair<>( 2 , "pear" );
boolean same = Util.compare(p1, p2);
|
边界符
现在我们要实现这样一个功能,查找一个泛型数组中大于某个特定元素的个数,我们可以这样实现:
1
2
3
4
5
6
7
|
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
等原始类型,其他的类并不一定能使用操作符>
,所以编译器报错,那怎么解决这个问题呢?答案是使用边界符。
1
2
3
|
public interface Comparable<T> {
public int compareTo(T o);
}
|
做一个类似于下面这样的声明,这样就等于告诉编译器类型参数T
代表的都是实现了Comparable
接口的类,这样等于告诉编译器它们都至少实现了compareTo
方法。通过限定T extends Comparable 表明,T是实现了Comparable的接口的类型,因此也实现了compareTo方法,因此不会产生编译期错误。
1
2
3
4
5
6
7
|
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;
}
|
类型的多个限定时我们可以使用&来进行分割,并且限定的关键词只能使用extends。与此同时在接口与类型都存在的情况下,类只能放在第一个,并且只能有一个,如下所示:
1
|
<T extends Object&Comparable&Serializable>
|
通配符
在了解通配符之前,我们首先必须要澄清一个概念,还是借用我们上面定义的Box类,假设我们添加一个这样的方法:
1
|
public void boxTest(Box<Number> n) { /* ... */ }
|
那么现在Box<Number> n
允许接受什么类型的参数?我们是否能够传入Box<Integer>
或者Box<Double>
呢?答案是否定的,虽然Integer和Double是Number的子类,但是在泛型中Box<Integer>
或者Box<Double>
与Box<Number>
之间并没有任何的关系。这一点非常重要,接下来我们通过一个完整的例子来加深一下理解。
首先我们先定义几个简单的类,下面我们将用到它:
1
2
3
|
class Fruit {}
class Apple extends Fruit {}
class Orange extends Fruit {}
|
下面这个例子中,我们创建了一个泛型类Reader
,然后在f1()
中当我们尝试Fruit f = fruitReader.readExact(apples);
编译器会报错,因为List<Fruit>
与List<Apple>
之间并没有任何的关系。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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之间肯定是存在联系,然而编译器却无法识别,那怎么在泛型代码中解决这个问题呢?我们可以通过使用通配符来解决这个问题:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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元素呢?我们来尝试一下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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
它自身可以有多种含义:
1
2
3
|
List<? extends Fruit> flist = new ArrayList<Fruit>();
List<? extends Fruit> flist = new ArrayList<Apple>();
List<? extends Fruit> flist = new ArrayList<Orange>();
|
- 当我们尝试add一个Apple的时候,flist可能指向
new ArrayList<Orange>()
; - 当我们尝试add一个Orange的时候,flist可能指向
new ArrayList<Apple>()
; - 当我们尝试add一个Fruit的时候,这个Fruit可以是任何类型的Fruit,而flist可能只想某种特定类型的Fruit,编译器无法识别所以会报错。
所以对于实现了<? extends T>
的集合类只能将它视为Producer向外提供(get)元素,而不能作为Consumer来对外获取(add)元素。
如果我们要add元素应该怎么做呢?可以使用<? super T>
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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
,它可以有下面几种含义:
1
2
3
|
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”:
- “Producer Extends” – 如果你需要一个只读List,用它来produce T,那么使用
? extends T
。 - “Consumer Super” – 如果你需要一个只写List,用它来consume T,那么使用
? super T
。 - 如果需要同时读取以及写入,那么我们就不能使用通配符了。
如何阅读过一些Java集合类的源码,可以发现通常我们会将两者结合起来一起用,比如像下面这样:
1
2
3
4
5
6
|
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泛型只能用于在编译期间的静态类型检查,然后编译器生成的代码会擦除相应的类型信息,这样到了运行期间实际上JVM根本就知道泛型所代表的具体类型。这样做的目的是因为Java泛型是1.5之后才被引入的,为了保持向下的兼容性,所以只能做类型擦除来兼容以前的非泛型代码。
- 在Java中不允许创建泛型数组
- 无法对泛型代码直接使用
instanceof
关键字 - 利用类型参数创建实例的做法编译器不会通过:
1
2
3
4
|
public static <E> void append(List<E> list) {
E elem = new E(); // compile-time error
list.add(elem);
}
|
如果某些场景我们想要需要利用类型参数创建实例,可以利用反射解决这个问题:
1
2
3
4
|
public static <E> void append(List<E> list, Class<E> cls) throws Exception {
E elem = cls.newInstance(); // OK
list.add(elem);
}
|