Why are Java wrapper classes immutable?

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

    The wrapper classes are immutable because it just makes no sense to be mutable.

    Consider following code:

    int n = 5;
    n = 6;
    Integer N = new Integer(n);
    

    At first, it looks straightforward if you can change the value of N, just like you can change the value of n.

    But actually N is not a wrapper to n, but a wrapper to 6! Look at the following line again:

    Integer N = new Integer(n);
    

    You are actually passing the value of n, which is 6, to N. And since Java is pass-by-value, you cannot pass n into N, to make N a wrapper to n.

    So, if we did add a set method to the wrapper:

    Integer N = new Integer(n);
    N.setValue(7);
    print(N); // ok, now it is 7
    print(n); // oops, still 6!
    

    The value of n will not be changed and that will be confusing!

    Conclusion:

    1. wrapper classes are wrappers of values, not wrappers of the variables.

    2. it will be confusing if you did add a set method.

    3. if you know it is a wrapper of a value, you will no longer ask for a set method. For example, you will not do "6.setValue(7)".

    4. it's impossible to make a wrapper to a variable in Java.

    0 讨论(0)
  • 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.)

    0 讨论(0)
  • 2020-12-02 18:22

    Any object instance which has any mutable aspects must have a unique identity; otherwise, another object instances which at one moment happened to be identical in every way except for its identity might at some other moment be different in its mutable aspect. In many cases, though, it's useful for types not to have an identity--to be able to pass a "4" without having to worry about which "4" one is passing. While there are times when it may be helpful to have a mutable wrapper of a primitive or immutable type, there are many more times when it's useful to have a type where all instances that hold the same data at some moment in time may be regarded as interchangeable.

    0 讨论(0)
提交回复
热议问题