类型参数: ArrayList<String> files = new ArrayList<>()
(String便是类型参数,且构造器中可省去,省去的类型依据变量的类型推断) 泛型类:
具有一个或多个类型变量的类。
public class Pair<T> { private T first; private T second; public Pair() {first = null;second = null ;} public Pair(T first,T second) {this.first = first;this.second = second;} public T getFirst() {return first;} public T getSecond() {return second ;} public void setFirst(T newValue) {first = newValue;} public void setSecond(T newValue) {second = newValue;} } //可以有多个类型变量 :public calss Pair<T,U>{...}(通常事大写的形式) 复制代码
泛型方法:类型变量放在修饰符的后面,返回类型的前面(该方法既可以放在普通类,也可以放在泛型类)
class ArrayAlg { public static <T> T getMiddle(T... a) { return a[a.length/2]; } } 复制代码
泛型方法的调用:
String middle = ArrayAlg.<String>getMiddle("John","A","Public"); <String>
public static <T extends Comparable> T min(T[] a) { if(a == null || a.length == 0) return null; T smallest = a[0]; for(int i = 0 ;i < a.length;i++) if(smallest.compareTo(a[i]) > 0) smallest = a[i]; return smallest; } 复制代码
extends T extends Comparable & Serializable
public class Pair { private Object first; private Object second; public Pair() {first = null;second = null ;} public Pair(Object first,Object second) {this.first = first;this.second = second;} public Object getFirst() {return first;} public Object getSecond() {return second ;} public void setFirst(Object newValue) {first = newValue;} public void setSecond(Object newValue) {second = newValue;} } 复制代码
public class Interval<T extends Comparable & Serializable > implements Serializable { private T lower; private T upper; ... public Interval(T first,Ts econd) { if(first.compareTo(second)<=0){lower=first;upper=second;} else{lower=second;upper=first;} } } //原始类型 public class Interval implements Serializable { private Comparable lower; private Coiparable upper; .... public Interval(Coiparable first,Coiparable second){...} } 复制代码
为了提高效率,最好将标签接口(没有方法的接口)放在边界末尾 翻译泛型表达式:调用泛型方法,若擦除返回类型,编译器插入强制类型转换 桥方法:为了解决多态与类型擦除的冲突 Java泛型转换的事实:
Pair<double>
,只有 Pair<Double>
Pair<String>[] T = new Pair<String>[10];
,声明变量 Pair<String>[] T
还是可以的, 原因:对于泛型类型,即使通过了数组存储检查,还是导致类型错误。 publicPair(){first=newT();second=newT();}//Error
(类型擦除将T改变成Object,解决方法: javaSE之后可以让调用者提供构造器表达式,传统的办法是使用 Class.newInstance
构造泛型对象) Pair<T>
与 Pair<S>
是没有关系的