为什么java.util.ArrayList中不允许原始数据类型?

为什么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.