为什么 Java 泛型不支持原始类型? [英] Why don't Java Generics support primitive types?

查看:29
本文介绍了为什么 Java 泛型不支持原始类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 Java 中的泛型适用于类而不适用于原始类型?

Why do generics in Java work with classes but not with primitive types?

例如,这很好用:

List<Integer> foo = new ArrayList<Integer>();

但这是不允许的:

List<int> bar = new ArrayList<int>();

推荐答案

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.

这篇关于为什么 Java 泛型不支持原始类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆