Why does the default Object.toString() return a he

2019-01-12 06:03发布

问题:

I'm curious why Object.toString() returns this:

return getClass().getName() + "@" + Integer.toHexString(hashCode());

as opposed to this:

return getClass().getName() + "@" + hashCode();

What benefits does displaying the hash code as a hex rather than a decimal buy you?

回答1:

Object.hashCode used to be computed based on a memory location where the object is located. Memory locations are almost universally displayed as hexadecimal.

The default return value of toString isn’t so much interested in the hash code but rather in a way to uniquely identify the object for the purpose of debugging, and the hash code serve well for the purpose of identification (in fact, the combination of class name + memory address is truly unique; and while a hash code isn’t guaranteed to be unique, it often comes close).



回答2:

I don't like the accepted answer. Here is my answer.

Short answer: because hex is easier to memorize, since a number expressed in hex is shorter and has a larger character variety than the same number expressed in decimal.

Longer answer: You are not going to be using the hash code to do arithmetic with it in your head, so you don't really need it to be in decimal. On the other hand, you are very likely going to be using it in the only way that it is intended to be used, that is, to tell whether two hash codes refer to the same object, or to different objects. In other words, you will be using it as a unique identifier or mnemonic for an object. Thus, the fact that it is a number is irrelevant; you might as well think of it as a hash string. Well, it just so happens that our brains find it a lot easier to retain (for the purpose of comparison) short strings consisting of 16 different characters, than longer strings consisting of only 10 different characters.