Integer as primitive type

前端 未结 4 510
不知归路
不知归路 2020-12-19 04:45

Why there is primitive type for integer(int) even though we have an object for integer as Integer? But the same is not with String type. There is no such primitive type for

4条回答
  •  粉色の甜心
    2020-12-19 05:45

    Speed. It's much faster for machine code to add two int's using native CPU instructions, rather than having to take two Integer objects, extract the int values from them, then add those, creating a new result Integer object to contain the result. (how JNI maps primitives)

    Strings are complex, have many methods, and as such have no machine code counterpoint. They are promoted to a true Object. Also, a String shares state with other Strings created with the same value. No primitive value shares state with other primitive values like this. (immutable can be shared | primitive no sharing)

提交回复
热议问题