Using int vs Integer

后端 未结 9 1445
抹茶落季
抹茶落季 2020-12-01 01:28

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         


        
相关标签:
9条回答
  • 2020-12-01 02:00

    Promote primitive types always where it is possible.

    primitive types can not be used as GenericArgument or a null.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-01 02:05

    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.

    0 讨论(0)
提交回复
热议问题