为什么java.util.ArrayList中不允许原始数据类型? [英] Why primitive datatypes are not allowed in java.util.ArrayList?

查看:300
本文介绍了为什么java.util.ArrayList中不允许原始数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在Java集合中存储原始值?

ArrayList仅接受引用类型作为其元素,而不接受基本数据类型。
尝试这样做时会产生编译时错误。

ArrayList accepts only reference types as its element, not primitive datatypes. When trying to do so it produces a compile time error.

这背后的概念是什么?这似乎是一种限制,不是吗?

What is the concept behind this? It seems like a limitation, is it not?

推荐答案

java的所有集合类都存储了它们收集的对象的内存位置。原始值不适合到同一个定义。

为了避免这个问题,JDK5及以后的 autoboxing - 其中基元被转换为适当的对象,当它们从集合中添加或读取时返回。

All collection classes of java store memory location of the objects they collect. The primitive values do not fit in to the same definition.
To circumvent this problem, JDK5 and onwards have autoboxing - wherein the primitives are converted to appropriate objects and back when they are added or read from the collections.

如果查看ArrayList源代码,它会使用Object数组来存储值。当您尝试将基元类型存储在集合中时,这就是自动装箱发生的原因之一。

If you look at the ArrayList source code, it uses Object array to store the values. This is one of the reason autoboxing happens when you try to store the primitive types in collections.

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

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