Why does the default Object.toString() include the hashcode?

前端 未结 3 645
别跟我提以往
别跟我提以往 2020-11-22 09:40

If you execute:

System.out.println(someObj.toString());

you probably see the output like

someObjectClassname@hashcod

相关标签:
3条回答
  • 2020-11-22 09:54

    Adding something useful.

    Some newbies may be confused as to why the hascode value returned via toString() is different than what is returned via hashCode(). This is because the toString() method returns a hex representaion of the same hashcode .

    Integer.toHexString(object.hashCode()); will return the same value returned by object.toString().

    0 讨论(0)
  • 2020-11-22 10:03

    The object hash code is the only standard identifier that might allow you to tell different arbitrary objects apart in Java. It's not necessarily unique, but equal objects normally have the same hash code.

    The default toString() method shows the object class and its hash code so that you can hopefully tell different object instances apart. Since it is also used by default in error messages, this makes quite a bit of sense.

    See the description of the hashCode() method for more information.

    0 讨论(0)
  • 2020-11-22 10:12

    From the javadocs:

    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.)

    The hashCode appears in the string representation of the object so that you can distinguish this object from other objects of the same class. This can be useful for debugging.

    0 讨论(0)
提交回复
热议问题