Why do people still use primitive types in Java?

后端 未结 21 2244
暗喜
暗喜 2020-11-22 15:11

Since Java 5, we\'ve had boxing/unboxing of primitive types so that int is wrapped to be java.lang.Integer, and so and and so forth.

I see

21条回答
  •  忘了有多久
    2020-11-22 15:28

    Couple of reasons not to get rid of primitives:

    • Backwards compatability.

    If it's eliminated, any old programs wouldn't even run.

    • JVM rewrite.

    The entire JVM would have to be rewritten to support this new thing.

    • Larger memory footprint.

    You'd need to store the value and the reference, which uses more memory. If you have a huge array of bytes, using byte's is significantly smaller than using Byte's.

    • Null pointer issues.

    Declaring int i then doing stuff with i would result in no issues, but declaring Integer i and then doing the same would result in an NPE.

    • Equality issues.

    Consider this code:

    Integer i1 = 5;
    Integer i2 = 5;
    
    i1 == i2; // Currently would be false.
    

    Would be false. Operators would have to be overloaded, and that would result in a major rewrite of stuff.

    • Slow

    Object wrappers are significantly slower than their primitive counterparts.

提交回复
热议问题