JAVA泛型
(github地址: https://github.com/liufeiSAP/javaStudy)
泛型类:
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<Integer> integerBox = new Box<Integer>();Box<Double> doubleBox = new Box<Double>();Box<String> stringBox = new Box<String>();泛型方法:
声明一个泛型方法很简单,只要在返回类型前面加上一个类似 <T> 或者<K, V>的形式:
限定符:
查找一个泛型数组中大于某个特定元素的个数:
错误写法:
public static <T> int countGreaterThan(T[] anArray, T elem) { int count = 0; for (T e : anArray) if (e > elem) // compiler error, 不能保证任意类型都是可以比较的。 ++count; return count;}正确写法:
做一个类似于下面这样的声明,这样就等于告诉编译器类型参数
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;}注意: 这里可以参考String的定义:
public final class String implements Serializable, Comparable<String>, CharSequence
通配符:
有如下函数定义: 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 {}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); 相当于实参是List<apple>,而形参是List<frut>, 两者没有联系,虽然apple是frut的子类 } public static void main(String[] args) { f1(); }}正确示例:
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原则:
问题: 上面可以取元素,是否可以往List中add元素。
List<? extends Fruit> flist = new ArrayList<Apple>(); 答案是否定,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>: 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(); }}注意: <? extends T> 和 <? super T> 一般只作为函数的形参使用。一定要弄明白两者谁可以get, 谁可以add. 规律是: ”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泛型很大程度上只能提供静态类型检查,然后类型的信息就会被擦除
(1):在Java中不允许创建泛型数组,类似下面这样的做法编译器会报错:
|
1
|
List<Integer>[] arrayOfLists = new List<Integer>[2]; // compile-time error |
也就是说下面的这个例子是不可以的:
List<String>[] ls = new ArrayList<String>[10];
而使用通配符创建泛型数组是可以的,如下面这个例子:
List<?>[] ls = new ArrayList<?>[10]; 这样也是可以的:List<String>[] ls = new ArrayList[10];
(2):我们无法对泛型代码直接使用
instanceof关键字最后: 通配符是为了解决,在函数传参的时候, “虽然Number和Integer是继承关系,但是 List<Number> 和 List<Integer> 没有关系” 这个问题而提出的,
并且可以定义通配符的数组(单是不能定义泛型数组)。
补充: <T> 和 <?> 的区别:
https://www.zhihu.com/question/31429113
类型参数“<T>”主要用于声明泛型类或泛型方法。 无界通配符“<?>”主要用于使用泛型类或泛型方法。
List<?> cc = new ArrayList<String>();
cc.add("fd"); // 编译有错误
实际更常用的是<? extends XXX>或者<? super XXX>两种,带有上下界的通配符

浙公网安备 33010602011771号