我正在阅读 Joshua Bloch 所著的《Effective Java》第二版。
在本段中,他提到:
Many classes in the Java platform libraries, such as String, Integer, and Date, include in their specifications the exact value returned by their hashCode method as a function of the instance value. This is generally not a good idea, as it severely limits your ability to improve the hash function in future releases. If you leave the details of a hash function unspecified and a flaw is found or a better hash function discovered, you can change the hash function in a subsequent release, confident that no clients depend on the exact values returned by the hash function.
任何人都可以分享一些他所说的“精确”值的见解吗?我查看了 String 实现类,但仍然无法理解他的意思...
提前致谢!
最佳答案
来自String.hashCode()
:
Returns a hash code for this string. The hash code for a String object is computed as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
通过在 javadoc 中给出定义,人们可以编写完全依赖于该哈希算法的代码。在未来版本中更改哈希算法将破坏该代码。
关于java - 他们的 hashCode 返回的确切值意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40788006/