Home  >  Q&A  >  body text

java怎么打印每个对象的内存地址呢?hashcode能代表内存地址的不同吗?

java怎么打印每个对象的内存地址呢?hashcode能代表内存地址的不同吗?

黄舟黄舟2713 days ago568

reply all(4)I'll reply

  • 黄舟

    黄舟2017-04-18 10:18:13

    1. I remember it’s not allowed. What is the reason for you to print the memory address?

    2. Hashcode does not necessarily mean that the memory addresses are different. Different JVMs have different implementations.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:18:13

    Object’s hashCode() returns the memory address by default, but hashCode() can be rewritten, so hashCode() cannot represent different memory addresses

    The System.identityHashCode(Object) method can return the memory address of the object, regardless of whether the object’s class overrides the hashCode() method

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 10:18:13

    The toString method in the Java Object class prints the address of the reference variable by default. If it does not print the address, then toString has been overridden in the subclass. You can try to rewrite toString

    reply
    0
  • PHPz

    PHPz2017-04-18 10:18:13

    Read the JDK API carefully.
    The general protocol of hashCode is:

    • During the execution of a Java application, the hashCode method must consistently return the same integer when called multiple times on the same object, provided that the information used to equals the objects is not modified. This integer does not need to be consistent from one execution of an application to another execution of the same application.

    • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

    • If two objects are not equal according to the equals(java.lang.Object) method, then calling the hashCode method on either object does not necessarily produce different integer results. However, programmers should be aware that generating different integer results for unequal objects can improve hash table performance.
      In fact, the hashCode method defined by the Object class does return different integers for different objects. (This is typically accomplished by converting the object's internal address to an integer, but the JavaTM programming language does not require this implementation technique.)

    reply
    0
  • Cancelreply