Boxing
[comp1110-8P]
Boxing
[comp1110-8P]When using generic types, a key restriction on type arguments is that they can only be reference types.
That is, one cannot have, say, a List<int>.
To cope with this, Java has a reference type called a wrapper class corresponding to each value type:
Integercorresponds tointCharactercorresponds tocharBooleancorresponds tobooleanBytecorresponds tobyteLongcorresponds tolongShortcorresponds toshortFloatcorresponds tofloatDoublecorresponds todouble
Any such wrapper class is treated specially, so you can assign to and from the wrapped type as if they were the same:
This is called autoboxing; putting an int value into an Integer is called boxing, and the reverse operation is called unboxing.
To have a list of integers, then, you'd use the type List<Integer>.
The reason we have the primitive value types at all is that they are much better for performance.
Creating an instance of Integer, on the other hand, requires us to allocate space on the heap, which is expensive.
Since these are objects, it is also important to note that == does not express equality on the wrapper classes.
You may different Integer objects representing the same integer value.