Why String class is immutable even though it has a non -final field called “hash”

前端 未结 5 1770
故里飘歌
故里飘歌 2021-02-02 11:23

I was reading through Item 15 of Effective Java by Joshua Bloch. Inside Item 15 which speaks about \'minimizing mutability\' he mentions five rules to make objects immutable. On

5条回答
  •  日久生厌
    2021-02-02 11:33

    To create a object immutable You need to make the class final and all its member final so that once objects gets crated no one can modify its state. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.

    EDIT:

    Notice : When hashing a string, Java also caches the hash value in the hash attribute, but only if the result is different from zero.

提交回复
热议问题