Why Wrapper class like Boolean in java is immutable?

前端 未结 4 2143
无人及你
无人及你 2021-01-05 15:23

I can\'t see the reason why the Boolean wrapper classes were made Immutable.

Why the Boolean Wrapper was not implemented like MutableBoolean in Commons lang which a

4条回答
  •  情书的邮戳
    2021-01-05 15:43

    Wrapper classes in Java are immutable so the runtime can have only two Boolean objects - one for true, one for false - and every variable is a reference to one of those two. And since they can never be changed, you know they'll never be pulled out from under you. Not only does this save memory, it makes your code easier to reason about - since the wrapper classes you're passing around you know will never have their value change, they won't suddenly jump to a new value because they're accidentally a reference to the same value elsewhere.

    Similarly, Integer has a cache of all signed byte values - -128 to 127 - so the runtime doesn't have to have extra instances of those common Integer values.

提交回复
热议问题