Why are Java wrapper classes immutable?

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

    Here is an example where it would be quite bad when Integer would be mutable

    class Foo{
        private Integer value;
        public set(Integer value) { this.value = value; }
    }
    
    /* ... */
    
    Foo foo1 = new Foo();
    Foo foo2 = new Foo();
    Foo foo3 = new Foo();
    Integer i = new Integer(1);
    foo1.set(i);
    ++i;
    foo2.set(i);
    ++i;
    foo3.set(i);
    

    Which are the values of foo1, foo2 and foo3 now? You would expect them to be 1, 2 and 3. But when Integer would be mutable, they would now all be 3 because Foo.value would all point to the same Integer object.

提交回复
热议问题