1.泛型也可以应用于接口。生成器是专门负责创建对象类,在生成器中只定义一个方法,用来产生新的对象。
public class Test17 { public static void main(String[] args) { B2 b = new B2(); b.a("hello"); } } interface A2<T> { public void a(T t); } class B2<T> implements A2<T> { @Override public void a(T t) { System.out.println(t.toString()); } } class C2 implements A2<String> { @Override public void a(String t) { System.out.println(t.toString()); } }
2.泛型方法:要定义泛型方法,只需将泛型参数列表置于返回值前。相比泛型类,优先使用泛型方法。static方法无法访问泛型类类型参数,只能使用泛型方法。当使用泛型类时,必须在创建对象的时候指定类型参数的值。而使用泛型方法的时候,通常不必指定参数类型,因为编译器会找出具体类型,这称为类型参数推断。
class Man { } public class Test18 { public <T> T t(Class<T> c) throws InstantiationException, IllegalAccessException { T t = c.newInstance(); return t; } public static void main(String[] args) throws InstantiationException, IllegalAccessException { Test18 t1 = new Test18(); Object o = t1.t(Man.class); System.out.println(o); } }
3.RandomList:作为容器的的另一个例子,我们需要一个持有特定类型对象的列表,每次调用其上的select()方法时,可以随机地选取一个元素。
public class Test19<T> { private ArrayList<T> a = new ArrayList<T>(); private Random r = new Random(47); public void add(T t) { a.add(t); } public T select() { return a.get(r.nextInt(a.size())); } public static void main(String[] args) { Test19<String> rs = new Test19<String>(); for (String s : ("Hello World " + "Hello Java").split(" ")) rs.add(s); for (int i = 0; i < 11; i++) System.out.print(rs.select() + " "); } }