Java Object.hashCode() - address or random()?

后端 未结 3 1104
梦如初夏
梦如初夏 2020-11-28 10:44

I\'m trying to understand the native implementation of the hashCode() method. What exactly does this method return? Is it a memory address or is it a random val

3条回答
  •  日久生厌
    2020-11-28 11:14

    From the documentation:

    As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

    So it may be related to a memory address, but it doesn't have to be - and you definitely shouldn't make any assumption about it being related to memory at all.

    Nothing you do with a hash code should care about this at all. The only things you should infer from hash codes are:

    • If the hash codes of two objects are the same, they may be equal objects
    • If the hash codes of two objects are different, they are not equal objects (assuming a correct implementation, whether overridden or not)

提交回复
热议问题