他们的 hashCode 返回的确切值是什么意思?

What does exact value returned by their hashCode mean?

我正在阅读 Joshua Bloch 的 Effective Java 第 2 版。

在这一段中,他提到:

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.

任何人都可以分享一些见解,他所说的 'exact' 价值观是什么意思。我查看了 String 实现 class 但仍然无法理解他的意思...

提前致谢!

来自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 中给出定义,人们可以编写完全依赖于该哈希算法的代码。在未来的版本中更改哈希算法将破坏该代码。

表示hashCode()返回的值在Javadoc中有规定

例如

  • 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]
    
  • Integer.hashCode():

    [Returns] a hash code value for this object, equal to the primitive int value represented by this Integer object.

  • Date.hashCode():

    Returns a hash code value for this object. The result is the exclusive OR of the two halves of the primitive long value returned by the getTime() method. That is, the hash code is the value of the expression:

    (int)(this.getTime()^(this.getTime() >>> 32))
    

如果您查看 java.lang.String.hashCode() 的 API 文档,它准确描述了该方法的实现方式:

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]

using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)

Bloch 所说的是 类 如 String 在 API 文档中描述实现细节是错误的,因为这意味着程序员可以指望hashCode 方法正在以这种方式实现。如果在未来的 Java 版本中,Oracle 想要实施一种不同的、可能更有效的算法来计算字符串的哈希码,那么这将是一个向后兼容性问题——与以前的 [= 相比,行为可能会发生变化24=] 个版本。

通过在API文档中详细描述实现,其实现方式已成为JavaAPI.

官方规范的一部分

一般来说,API 文档应该只描述该方法的目的,而不是确切地描述它是如何实现的。