1.泛型类
不仅使用通配符时可以设置形参上限,定义类型形参时也可以设置类型上限。
public class Apple<T extends Number> { private T info; public static void main(String[] args) { Apple<Integer> intApple=new Apple<>(); //编译不通过,Bound mismatch //Apple<String> strApple=new Apple<>(); } }
而且Java可以在定义形参时设置一个父类上限,多个接口上限。下列代码要求T类型必须是Number类的子类,而且必须实现了java.io.Seriazable接口。
public class Apple<T extends Number & java.io.Serializable> {...}
2.泛型方法
可以单独为方法指定泛型形参。在该方法内部可以把指定的泛型形参当成正常类型使用。
public class GenericMethodTest { static <T> void fromArrayToCollections(T[] a,Collection<T> c){ for(T o: a){ c.add(o); } } public static void main(String[] args) { Object [] oa=new Object[100]; Collection<Object> co=new ArrayList<>(); //下列T代表Object类型 fromArrayToCollections(oa, co); String [] sa=new String[100]; Collection<String> cs=new ArrayList<>(); //下列T代表String类型 fromArrayToCollections(sa, cs); //下列T代表Object类型 fromArrayToCollections(sa, co); Number [] na=new Number[100]; //The method fromArrayToCollections(T[], Collection<T>) //in the type GenericMethodTest is not applicable for //the arguments (Number[], Collection<String>) //fromArrayToCollections(na, cs); } }