Why primitive datatypes are not allowed in java.util.ArrayList? [duplicate]

我的未来我决定 提交于 2019-12-18 05:49:26

问题


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?


回答1:


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.

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.




回答2:


Because Java can only use class (and not primitive types) and arrays (also arrays for primitives) for generics (between < and >).

List list; That is also a reason why there are wrapper classes for primitive types:

int -> Integer

boolean -> Boolean

double -> Double

byte -> Byte etc...



来源:https://stackoverflow.com/questions/5414920/why-primitive-datatypes-are-not-allowed-in-java-util-arraylist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!