Why are Java wrapper classes immutable?

前端 未结 9 1674
日久生厌
日久生厌 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:22

    However, wrapper classes represent primitive types, and primitive types (except String) are mutable.

    No they're not (and String isn't a primitive type). But since primitive types aren't objects anyway, they can't really be called mutable / immutable in the first place.

    Regardless, the fact that wrapper classes are immutable is a design decision (a good one IMO.) They could have just has easily been made mutable, or mutable alternatives provided too (indeed several libraries provide this, and other languages do by default.)

提交回复
热议问题