how caching hashcode works in Java as suggested by Joshua Bloch in effective java?

前端 未结 3 1615
旧巷少年郎
旧巷少年郎 2020-12-14 04:53

I have the following piece of code from effective java by Joshua Bloch (Item 9, chapter 3, page 49)

If a class is immutable and the cost of computing

3条回答
  •  无人及你
    2020-12-14 05:28

    The hashCode variable in an instance variable, and it's not initialized explicitly, so Java intializes it to 0 (JLS Section 4.12.5). The comparison result == 0 is in effect a check to see if result has been assigned a presumably non-zero hash code. If it hasn't been assigned yet, then it performs the calculation, else it just returns the previously computed hash code.

提交回复
热议问题