Why does the default Object.toString() return a hex representation of the hashCode?

与世无争的帅哥 提交于 2019-11-27 09:28:00
Konrad Rudolph

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!