java - 他们的 hashCode 返回的确切值意味着什么?

标签 java hashcode

我正在阅读 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/

相关文章:

java - Spring 3.0 webapp NoClassDefFoundError - 类路径问题

java - 在不使用集合的情况下重复字符串中的单词

java - 从父类(super class)对象列表获取子类

java - 向上转型和包装类

java - 如何更正 hashCode() 方法以正确使用 HashSet 集合

java - 无冲突计算整数数组散列的最快方法

java - Java hashCode 方法是否同时进行转换和压缩?

java - Spring-AMQP 事务性发布无异常

c# - 用 C 重写 GetHashCode32(string s) 方法

c# - 如何使用项目的哈希值检查 HashSet 是否包含项目?