- 什么是泛型的擦除?
public class Test<S> { S name; public S getName() { return name; } public void setName(S name) { this.name = name; } public static void main(String[] args) throws Exception { Test<Integer> test1 = new Test<>(); test1.setName(1); Test test2 = test1; //泛型的擦除,编译过程中丢失了具体的参数类型 Integer name2 = (Integer) test2.getName(); //运行时候对象的类型没变,擦除只是发生在编译阶段 System.out.println(test2.getName().getClass()); } }
- 什么是泛型的转换?
public class Test<S> { S name; public S getName() { return name; } public void setName(S name) { this.name = name; } public static void main(String[] args) throws Exception { List<Integer> list = new ArrayList<>(2); list.add(1); list.add(2); List list1 = list; List<String> list2 = list1; System.out.println((String)list2.get(0)); } }