Why Java Collections Cannot Directly Store Primitives Types?
Primitive types are the most basic data types available within the Java language. Such types serve only one purpose — containing pure, simple values of a kind. 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.
Invalid : vector.addElement(3) ; Valid : vector.addElelment("3") ;
- Java primitive types are not referenced types. For example, int is not an Object.
- Java does generics using type-erasure of reference types. For example, A List<?> is really a List<Object> at run-time.
Collections are the framework used to store and manipulate a group of objects. Java Collection means a single unit of objects. Since the above two statements are true, generic Java collections can not store primitive types directly.
Wrapper Class provides a way to use primitive data types (int, boolean, etc..) as objects or a Wrapper class is a class whose object wraps or contains primitive data types. It gives birth to two concepts as follows:
|Primitive Data Type||Wrapper Class|
Autoboxing is the automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing. For instance:
- Conversion of int to Integer
- Conversion of long to Long
- Conversion of double to Double, etc.
Unboxing is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to long, Double to double, etc.
Illustration 2: Unboxing
Implementation: While using the collection java compiler create a wrapper Object from the primitive type and adds it to the collection using generics.
0 1 2 3 4 5 6 7 8 9
Example 2: Collections to store Primitive datatype
Successfully compiled and executed
Please Login to comment...