问题
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