Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

arraylist

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?

like image 320
Selvin Avatar asked Mar 24 '11 04:03

Selvin


People also ask

Why primitive data types are not used in ArrayList?

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.

Why primitive data types are not allowed in Java generics?

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.

Why primitive data types are not allowed in Collections?

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.

Can an ArrayList have different data 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.


1 Answers

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

like image 96
CMR Avatar answered Sep 23 '22 01:09

CMR