Does Object.toString or Object.hashCode ever give the memory address of the object

后端 未结 1 723
走了就别回头了
走了就别回头了 2020-12-06 22:19

It is often claimed that the implementation of Object.hashCode() (the default implementation for all objects) gives the memory address of the object. That claim

相关标签:
1条回答
  • 2020-12-06 22:43

    Since the default hash code of an object does not need to be unique, returning the whole address is not necessary. An implementation could grab a group of bits from the address - say, bits 3 through 35 on a 64-bit system, or a XOR between the upper 32 bits and the lower 32 bits, or simply the lower 32 bits.

    But as many objects would then have similar addresses [due to garbage collection], that would be a poor choice for a hash code.

    Hash codes that are numerically close to each other are OK. Even a small number of identical hash codes would not create a problem, because equality is used to resolve any ties. The situations when the default hash code implementation is used are generally limited, because objects that are used as keys in hash-based containers are expected to provide "good" implementations of hashCode method.

    Oracle says that the default implementation of their JVM uses the internal address of the object, whatever that means, to compute its hashCode. However, other JVM implementations are not required to do the same:

    Here is a quote from Oracle's 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 Java™ programming language.)

    You can find the actual implementation of the algorithm here. Search for get_next_hash function for details. It appears that computing hash based on address is done with a simple conversion:

    value = intptr_t(obj) ;
    
    0 讨论(0)
提交回复
热议问题