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

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

    String is immutable because as far as its users are concerned, it can never be modified and will always look the same to all threads.

    hashCode() is computed using the racy single-check idiom (EJ item 71), and it's safe because it doesn't hurt anybody if hashCode() is computed more than once accidentally.

    Making all fields final is the easiest and simplest way to make classes immutable, but it's not strictly required. So long as all methods return the same thing no matter which thread calls it when, the class is immutable.

提交回复
热议问题