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

前端 未结 5 1767
故里飘歌
故里飘歌 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:30

    Even though String is immutable, it can change through reflection. If you make hash final, you could mess things up royally were this to occur. The hash field is different too in that it is there mainly as a cache, a way to speed up the calculation of hashCode() and should really be thought of as a calculated field, less so a constant.

提交回复
热议问题