基本的泛型:
public class GenericsTest {
public static void main(String[] args) {
ArrayList<String> collection1 = new ArrayList();
collection1.add("abc");
String str1 = collection1.get(0);
System.out.println(str1);
ArrayList<Integer> collection2 = new ArrayList();
collection2.add(3);
int int2 = collection2.get(0);
System.out.println(int2);
}
}
输出结果很明显是abc和3
现在用放射看看他们的字节码是不是同一份:
在程序中加入下面代码:
System.out.println(collection1.getClass()==collection2.getClass());
这行代码的输出结果是true------说明ArrayList虽然有不同的泛型在内存中字节码只有一份,就是编译完成之后就没有类型信息了,已经去类型化了,为了证明这个可以行,用反射向ArrayList<Integer> collection2 = new ArrayList();中增加String类型的对象。
首先若是直接collection2.add("abc");编译器肯定是会报错的。因为collection2是integer类型的。
下面用反射进行实验:
输出结果为:
abc
3
true
abc