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

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

问题描述

为什么Java中的泛型使用类但不使用原始类型?

例如,这可以正常工作:

 列表<整数> foo = new ArrayList< Integer>(); 

但这是不允许的:

 列表与LT; INT> bar = new ArrayList< int>(); 


解决方案

Java中的泛型是一个完全的编译时构造 - 编译器将所有通用用途转换为正确的类型。这是为了保持向前兼容以前的JVM运行时。



这:

 列表与LT; 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 ),而原始类型则不是。所以他们不能用于泛型。


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

For example, this works fine:

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

but this is not allowed:

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

解决方案

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.

This:

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

gets turned into (roughly):

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

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天全站免登陆