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

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

问题描述

<块引用>

可能的重复:
在 Java 集合中存储原始值?

ArrayList 只接受引用类型作为其元素,而不接受原始数据类型.尝试这样做时会产生编译时错误.

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

解决方案

java 的所有集合类都存储它们所收集对象的内存位置.原始值不适合相同的定义.
为了规避这个问题,JDK5 及以后有自动装箱 - 其中原语被转换为适当的对象,并在它们被添加或从集合中读取时返回.请参阅有关此主题的官方 JDK 教程.>

检查ArrayList 的 JDK5 源代码 有助于更好地理解:创建 ArrayList 包括将 Object[] 数组转换为 E[].

Possible Duplicate:
Storing primitive values in a Java collection?

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?

解决方案

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. Refer to the official JDK tutorial on this topic.

Checking the JDK5 source code for ArrayList helps better understanding: creating an ArrayList<E> includes casting an Object[] array to E[].

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

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