为什么不能为泛型自动填充Java基本类型? [英] Why not auto-box Java primitive types for Generics?

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

问题描述

Java不允许在通用数据结构中使用基本类型。例如。的ArrayList< INT>不允许。原因是,原始类型不能直接转换为Object。但是,Java 1.5确实支持自动装箱,并且包装类在普通数据结构中工作。那么为什么编译器不能将它自动装箱到ArrayList< Integer>?是否还有其他原因导致这种情况无法正常工作?

解决方案

据我了解,您提出的 ArrayList< int> 将与 ArrayList< Integer> 相同。是对的吗? (换句话说,在内部它仍然存储一个Integer;每次你把东西放进去或者把它拿出来,它会自动地对它进行box / unbox,但是autoboxing / autounboxing已经为 ArrayList< Integer> )



如果它是相同的,那么我不明白具有重复语法< int> 表示与< Integer> 相同的内容。 (实际上它会引入额外的问题,因为例如 int [] Integer [] ,所以如果你有 T [] ,并且 T int ,这是什么意思?)


Java does not allow primitive types to be used in generic data structures. E.g. ArrayList<int> is not allowed. The reason is, primitive types can not be directly converted to Object. However Java 1.5 does support auto-boxing, and wrapper classes work in generic data structures. So why couldn't the compiler auto-box it to ArrayList<Integer>? Are there any other reasons for why this can not work?

解决方案

So as far as I understand it, your proposed ArrayList<int> would be identical to ArrayList<Integer>. Is that right? (In other words, internally it still stores an Integer; and every time you put something in or get it out, it would automatically box/unbox it, but autoboxing/autounboxing already does that for ArrayList<Integer>.)

If it is the same, then I don't understand what is the utility of having a duplicate syntax <int> that means the same thing as <Integer>. (In fact it will introduce additional problems, because for example int[] is not the same runtime type as Integer[], so if you have T[], and T is int, what would it mean?)

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

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