泛型使用
编译时有效 运行时无效(类型擦除)
=================================================================
class Animal{}
class Dog extends Animal{}
class Cat extends Animal{}
class JiaFeiCat extends Cat{}
===================================================
===================================================
Kotlin
out T 等价于 ? extends T
in T 等价于 ? super T
还有 * 等价于 ?
类型擦除
ArrayList 插入后 元素的类型是被擦除的
通过反射插入可以看出来
private static void ceshi2(){
ArrayList<Integer> intList = new ArrayList<>();
intList.add(111);
try {
Method add = intList.getClass().getMethod("add",Object.class);
add.invoke(intList,"iffy");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("intList存储了:"+intList.size()+"个对象");
System.out.println("intList存储1的内容是:"+intList.get(0));
System.out.println("intList存储2的内容是:"+intList.get(1));
}
当get的时候不会被泛型强制转换回来,ArrayList的get代码
public E get(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
return (E) elementData[index];
}