I came across a class using Integer variables to capture size to be used in a for loop. Is this good practice or should we use the int primitive data type?
I
Promote primitive types always where it is possible.
primitive types can not be used as GenericArgument or a null.
If you can use int
do so. If the value can be null
or is used as an Object e.g. Generics, use Integer
Usually it doesn't matter which one you use but often int
performs slightly better.
This approach is not good in practice, use int
whenever possible. Usage of Integer
indicates that this particular variable can be null
(or it was inside a collection, damn generics...) - which is not the case.
Also using Integer
introduces an extra overhead of boxing and unboxing.