Hello All,
When i should go for wrapper class over primitive types? Or On what circumstance i should choose between wrapper / Primitive types?
Hello All,
When i should go for wrapper class over primitive types? Or On what circumstance i should choose between wrapper / Primitive types?
If you want to use Collections, you must use Wrapper classes.
Primitive types, are used for arrays. Also, to represent data that has no behaviour,for example, a counter, or a boolean condition.
Since autoboxing, the "when to use primitive or wrapper" frontier has become quite fuzzy.
But remember, Wrappers are objects, so you get all the fancy Java features. For example, you can use reflexion to create Integer objects, but not int values. Wrapper classes also have methods such as valueOf.
Generally, you should use primitive types unless you need an object for some reason (e.g. to put in a collection). Even then, consider a different approach that doesn't require a object if you want to maximize numeric performance. This is advised by the documentation, and this article demonstrates how auto-boxing can cause a large performance difference.
If you want to create a value type. Something like a ProductSKU or AirportCode.
When a primitive type (string in my examples) defines equality, you'll want to override equality.
I would only use the wrapper types if you have to.
In using them you don't gain much, besides the fact that they are Objects
.
And, you lose overhead in memory usage and time spent boxing/unboxing.
Others have mentioned that certain constructs such as Collections require objects, and that objects have more overhead than their primitive counterparts (memory & boxing).
Another consideration is:
It can be handy to initialise Objects to null, or send null parameters into a method/constructor to indicate state or function. This can't be done with primitives.
Many programmers initialise numbers to 0 (default) or -1 to signify this, but depending on the scenario, this may be incorrect or misleading.
This will also set the scene for a NullPointerException when something is being used incorrectly, which is much more programmer-friendly than some arbitrary but down the line.
Collections are the typical case for the simple Java wrapper objects. However, you might consider giving the Wrapper a more specific meaning in the code (value object).
IMHO there's almost always a benefit to use value objects when it boils down to readability and maintainance of the code. Wrapping simple data structures inside of objects when they have certain responsibilities often simplifies the code. This is something that is very important in Domain-Driven Design.
There is of course the performance issue, but I tend to ignore that until I have the possibility to measure the performance with proper data and do more directed actions towards the problematic area. It might also be easier to understand the performance issue if the code is easy to understand as well.