At a very abstract level I do know that wrapper classes, create an object of the primitive data type but I was curious as to why do we need to use wrapper classes and what benefits do they offer over primitive data types.
Collections in the first place, for example,List<Integer>
, you cannot use primitive int
here.
Actually any generic class / interface that can work with different object types like
public interface Callable<V> {
V call() throws Exception;
}
Note that wrapping is best done using not new Integer(i) but Integer.valueOf(i) the latter will try to use cache. Unwrapping is done as Integer.intValue(). These wrapping / unwrapping of primitives are so typical operations that Java 5 introduced autoboxing / unboxing
List<Integer> list = new ArrayList<>();
list.add(1);
int i = list.get(0);
this code is automatically converted by Java compiler into
list.add(Integer.valueIf(1));
int i = list.get(0).intValue(); // this is where NullPointerException sometimes happens
Wrapper classes are designed to add more functionality to the primitive types, so that they are compatible with generic code, using the Collection Framework, and many other benefits. However, they are not mean't to replace primitive types.
So, you should use wrappers only when necessary, such as when dealing with generics, because creating an object adds substantial overheads to your program. So, in normal cases, you should stick to primitives.
A wrapper type enables a primitive to hold more contextual meaning. For instance an integer could be anything, whereas a class called Hours, for example, gives the number meaning wherever it is used.
They also enable methods to be written that mutate the said primitive in a consistent and obvious way to consumers. Have a look at Domain Driven Design for more information surrounding this point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With