When to use primitive and when reference types in Java

后端 未结 11 557
旧时难觅i
旧时难觅i 2020-12-01 02:55

In which case should you use primitive types(int) or reference types (Integer)?

This question sparked my curiosity.

11条回答
  •  旧时难觅i
    2020-12-01 03:46

    Rather than calling them "complex types", you'd be best served thinking Integer, Double, etc. as "Classes", and int, double, etc. as "primitives".

    If you're doing any type of sophisticated math, the Class-based numeric representation like Integer and Double will be cumbersome and slow you down - many math operations can only be done with primitives.

    On the other hand, if you're trying to put your numbers into collections like Lists and Maps, those collections can only contain objects - and thus you must use (or convert to) classes like Integer and Double.

    Personally, I use primitives whenever I can get away with it, and only convert to the Class representations like Integer when it's time to do input or output, and the transport requires those representations.

    However, if you aren't doing any math at all, and instead are just passing the values straight through your code, you might save yourself some trouble by dealing with the Class-based forms (like Integer) exclusively.

提交回复
热议问题