1.用适配器仿真潜在类型机制:潜在类型机制是一种代码组织和服用机制。潜在类型机制实际上创建了一个包含所需方法的隐式接口,通过手工编写该接口,就可以解决。
interface Aa<T> { void a(T t); } class A<T> implements Aa<T> { private Collection<T> collection; public A(Collection<T> c) { this.collection = c; } @Override public void a(T t) { collection.add(t); } } public class Test7 { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); A<Integer> a1 = new A<>(list); a1.a(10); for (int i : list) { System.out.println(i); } } }
2.当你未碰巧拥有正确的接口时:使用潜在类型机制的参数化类型机制,才能真正实现泛化,情况就会不同。
class A { public static <T> void a(Collection<T> collection, Class<? extends T> c, int i) { for (int j = 0; j < i; j++) { try { collection.add(c.newInstance()); } catch (Exception e) { throw new RuntimeException(e); } } } } class B { private static long l = 0; private final long l1 = l++; @Override public String toString() { return getClass().getName() + " " + l1; } } class C extends B { } public class Test9 { public static void main(String[] args) { List<B> list = new ArrayList<>(); A.a(list, B.class, 3); A.a(list, C.class, 2); for (B c : list) { System.out.println(c); } } }