Are all final class immutable?

前端 未结 8 2344
一生所求
一生所求 2021-02-19 09:34

Are all final classes in Java immutable. String and Integer both are final classes and both are immutable i beleive.

8条回答
  •  醉酒成梦
    2021-02-19 10:01

    Further to the other responses, if you look at the code for java.lang.String you'll see it contains a field: hash, which is mutable and is in fact computed and stored when hashCode() is called for the first time.

    However, the class is still immutable: The hash field cannot be accessed directly or modified outside of the class.

    Also, you may notice a common approach within the JDK is the implementation of immutable wrappers that can be used to expose an object's internal state without allowing it to be modified; e.g.

    private final List values;
    
    public List getValues() {
      return Collections.unmodifiableList(values);
    }
    

提交回复
热议问题