引言
泛型是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>();
泛型方法
看完了泛型类,接下来我们来了解一下泛型方法。声明一个泛型方法很简单,只要在返回类型前面加上一个类似<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; }
}
我们可以像下面这样去调用泛型方法:
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自动推导出相应的类型参数:
pair<integer, string> p1 = new pair<>(1, "apple");
pair<integer, string> p2 = new pair<>(2, "pear");
boolean same = util.compare(p1, p2);
边界符
现在我们要实现这样一个功能,查找一个泛型数组中大于某个特定元素的个数,我们可以这样实现:
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>();
当我们尝试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>:
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”:
“producer extends” – 如果你需要一个只读list,用它来produce t,那么使用? extends t。
“consumer super” – 如果你需要一个只写list,用它来consume 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泛型讲解的详细内容。