Alex Rivera | Logout

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

Asked 2011-03-24T04:52:13.503
19

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?

Edit
Report

1 Answer

11

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[].

answered 2011-03-24T05:08:23.370

Your Answer