【发布时间】:2018-11-09 22:36:52
【问题描述】:
我最近开始从基础开始学习 Java,我遇到了这个问题 关于泛型类型的“小”误解,它提出了如下问题:
将参数化类型实例引用到其原始类型和 使用原始类型引用另一个原始类型实例?
我的意思是,这就是这个sn-p的区别:
ArrayList rawTypeList_NoRawInstance = new ArrayList</*Any type here*/>();
还有这个:
ArrayList rawTypeList_RawInstance = new ArrayList();
代码:
import java.util.*;
public class TestGenerics{
public static void main(String args[]){
ArrayList rawTypeList_RawInstance = new ArrayList();
ArrayList rawTypeList_NoRawInstance = new ArrayList<Integer>(); /* instead of Integer could be placed any kind of type, this
* is just an example */
rawTypeList_RawInstance.add("example RawInstance"); // warning launched
rawTypeList_NoRawInstance.add("example NoRawInstance"); // same warning here
System.out.println(rawTypeList_RawInstance.get(0)); // content showed without errors/warning
System.out.println(rawTypeList_NoRawInstance.get(0)); // same here
String exampleRawInstance1 = (String)rawTypeList_RawInstance.get(0); // raw type instance compiled without error
String exampleNoRawInstance1 = (String)rawTypeList_NoRawInstance.get(0); // Generic type -Integer- instance compiled without error
Integer exampleRawInstance2 = (Integer)rawTypeList_RawInstance.get(0); // ClassCastException as expected
Integer exampleNoRawInstance2 = (Integer)rawTypeList_NoRawInstance.get(0); // same here, logically
}
}
谁能解释一下其中的区别并举一些例子说明可能的不同后果?
【问题讨论】:
标签: java generics type-erasure raw-types