Why are Java wrapper classes immutable?

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

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

    Firstly, String isn't a primitive type.

    Secondly, it makes no sense to talk about the primitive types being mutable. If you change the value of a variable like this:

    int x = 5;
    x = 6;
    

    That's not changing the number 5 - it's changing the value of x.

    While the wrapper types could have been made mutable, it would have been annoying to do so, in my view. I frequently use readonly collections of these types, and wouldn't want them to be changeable. Very occasionally I want a mutable equivalent, but in that case it's easy enough to come up with one, or use the Atomic* classes.

    I find myself wishing that Date and Calendar were immutable far more often than I find myself wanting Integer to be mutable... (Of course I normally reach for Joda Time instead, but one of the benefits of Joda Time is immutability.)

提交回复
热议问题