Why are Java wrapper classes immutable?

前端 未结 9 1694
日久生厌
日久生厌 2020-12-02 17:25

I know the usual reasons that apply to general immutable classes, viz

  1. can not change as a side effect
  2. easy to reason about their state
  3. inhe
9条回答
  •  误落风尘
    2020-12-02 18:07

    The primitive types are mutable, but they are not shareable - that is no two sections of code will ever be referring to the same int variable (they are always passed by value). So you can change your copy and no one else sees the change, and vice versa. As Phillip shows in his answer, that would not be the case with mutable wrapper classes. So my guess is that they had a choice when the wrapped the primitive data types between:

    matching the fact that you can change the value of a primitive type,

    versus

    matching the fact that primitive types can be passed around and no changes by a user will be seen by any other user of the data.

    And they chose the latter, which required immutability.

提交回复
热议问题