Boxing and Unboxing in java

Boxing and Unboxing:

Suppose we want an array list of integers. Unfortunately, the type parameter inside the angle brackets cannot be a primitive type. It is not possible to form an ArrayList<int>. Here, the Integer wrapper class comes in. It is ok to declare an array list of Integer objects.
ArrayList<Integer> list = new ArrayList<Integer>();
Note: An ArrayList<Integer> is far less efficient than an int[] array because each value is separately wrapped inside an object. You would only want to use this construct for small collections when programmer convenience is more important than efficiency.
The call
list.add(3);
is automatically translated to
list.add(new Integer(3));
This conversion is called autoboxing.
Conversely, when you assign an Integer object to an int value, it is automatically unboxed. That is, the compiler translates
int n = list.get(i);
into
int n = list.get(i).intValue();

No comments:

Post a Comment