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?
They are used when there is a usage of the primitive data types in java structures that require objects such as JLists, ArrayLists. Now, in order to hold primitive data such as int and char in ArrayList are explained. Primitive data types cannot be stored in ArrayList but can be in Array.
Answer is Object is superclass of all objects and can represent any user defined object. Since all primitives doesn't inherit from "Object" so we can't use it as a generic type.
Since java is a Statically typed language where each variable and expression type is already known at compile-time, thus you can not define a new operation for such primitive types.
ArrayLists cannot hold primitive data types such as int, double, char, and long (they can hold String since String is an object, and wrapper class objects (Double, Integer). Like an array, it contains components that can be accessed using an integer index.
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[]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With