If you execute:
System.out.println(someObj.toString());
you probably see the output like
someObjectClassname@hashcodenumber
My question : Is开发者_JAVA百科 there any specific reason why hashCode number is displayed there?
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.
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()
.
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.
精彩评论