preface
- 基于Java 8 的generic的介绍
1.Generic(Why)
- 可以让某些运行期间出现的错误(例如cast),现在通过compile期间的强类型检查,来检出错误
- 可以通过Generic,来编写一个generic type的类或者接口的模板,这样可以创建基于某一特定功能但具有不同数据类型的类,也可以通过generic method来编写针对某些具有相同特性的队形进行操作generic方法
- 可以消除cast的使用
2.Generic class (What)
2.1 generic type
-
generic type的定义:就是在类型上参数化的泛型类或者接口
-
定义generic type 的模板(generic 类和接口都是这么定义的)
class name<T1, T2, ..., Tn> { /* ... */ }
例子:
/** * Generic version of the Box class. * @param <T> the type of the value being boxed */ public class Box<T> { // T stands for "Type" private T t; public void set(T t) { this.t = t; } public T get() { return t; } } public interface Pair<K, V> { public K getKey(); public V getValue(); } //多个 type parameter public class OrderedPair<K, V> implements Pair<K, V> { private K key; private V value; public OrderedPair(K key, V value) { this.key = key; this.value = value; } public K getKey() { return key; } public V getValue() { return value; } }
-
继承(inheritance),implement
-
继承或者实现的原则:
- 就是泛型父类或者接口的type parameter 在子类泛型中要保留下来,自己可以新增额外的type parameter
- 对于Parameterized type,只有相同type argument的的Parameterized type 父类和子类之间才存在subtype(父子的关系),如果不是相同的Parameterized type不同,则不存在subtype关系
-
例子
Box<Number> 跟 BOX<Integer>不存在父子关系 interface PayloadList<E,P> extends List<E> { void setPayload(int index, P val); ... }
-