java - hashcode是内存地址还是内存地址内容的整数?

标签 java hashcode

为什么这段代码给出负的哈希码?

import java.util.HashSet;
import java.util.Set;

public class Ab {

    /**
     * @param args
     */
    public static void main(String[] args) {
    String s1="Operations on a dynamic set can be grouped into two categories queries, which simply return information about the set, and modifying operations, which change the set. Here is a list of typical operations. Any specific application will usually   require only a few of these to be implemented Some dynamic sets presuppose that the keys are drawn from a totally ordere, such as the real numbers, or the set of all words under the usual alphabetic ordering. A total ordering allows us to define the minimum element of the set, for example, or to speak of the next element larger than a given element in a set.Operations on dynamic sets Operations on a dynamic set can be grouped into two categories: q";

    System.out.println(s1.hashCode());
    String s2="abc";
    System.out.println(s2.hashCode());
    }

}

最佳答案

String 类重写 hashCode() 以产生确定性结果。结果与内存地址无关。 String.hashCode() Javadoc显示用于计算它的公式:

The hash code for a String object is computed as s[0]*31^(n-1) + s1*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.)

请注意,即使对于相对较短的字符串,该值对于整数来说也可能太大。在计算过程中,每当发生溢出时,仅保留最低有效的 32 位。 在计算结束时,如果设置了结果整数的最高有效位,则该整数为负数,否则为正数。

关于java - hashcode是内存地址还是内存地址内容的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17481069/

相关文章:

java - Hibernate NOT IN 联结表上的子查询

java - 使用 Jaxb 和 JDK 9 的小程序中的非法反射访问

scala - 在 Scala 中实现 findOrCreate 池的最有效方法是什么?

哈希表和可比较对象中使用的 Java Null 对象

Java hashcode 方法错误

java - Teradata CLOB 和 JDBC : The Locator is invalid because it has been changed ERROR

java - 在什么时候值得在Java中重用数组?

java - Admob 原生快捷广告

hibernate - 我应该如何覆盖具有复合主键的实体中的 equals/hashCode?

java - 为什么 main 方法中 args 的哈希码仅限于某些值集?