且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么 Java 泛型不支持原始类型?

更新时间:2022-11-23 08:06:00

Java 中的泛型完全是编译时构造 - 编译器将所有泛型用途转换为正确类型的强制转换.这是为了保持与以前的 JVM 运行时的向后兼容性.

Generics in Java are an entirely compile-time construct - the compiler turns all generic uses into casts to the right type. This is to maintain backwards compatibility with previous JVM runtimes.

这个:

List<ClassA> list = new ArrayList<ClassA>();
list.add(new ClassA());
ClassA a = list.get(0);

变成(大致):

List list = new ArrayList();
list.add(new ClassA());
ClassA a = (ClassA)list.get(0);

因此,任何用作泛型的东西都必须可以转换为 Object(在这个例子中 get(0) 返回一个 Object),并且原始类型是'吨.所以它们不能用在泛型中.

So, anything that is used as generics has to be convertable to Object (in this example get(0) returns an Object), and the primitive types aren't. So they can't be used in generics.