Why are Java wrapper classes immutable?

前端 未结 9 1675
日久生厌
日久生厌 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.

提交回复
热议问题