哈希码是内存地址还是内存地址内容的整数? [英] Hashcode is memory address or integer number of content of memory address?

查看:403
本文介绍了哈希码是内存地址还是内存地址内容的整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么此代码会给出负的哈希码?

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 String class overrides hashCode() to produce deterministic results. The result has nothing to do with memory addresses. The String.hashCode() Javadoc shows the formula used to calculate it:

字符串对象的哈希码计算为 s [0] * 31 ^(n-1)+ s

The hash code for a String object is computed as s[0]*31^(n-1) + s1*31^(n-2) + ... + s[n-1]

使用int算术,其中s [i]是字符串的第i个字符,n是字符串的长度,^表示幂. (空字符串的哈希值为零.)

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位. 在计算结束时,如果设置了结果整数的最高有效位,则该整数为负,如果不是,则为正.

Note that for even relatively short strings the value can get too big for an integer. During the calculations, whenever an overflow occurs only the least significant 32 bits are kept. At the end of the calculation, if the most significant bit of the resulting integer is set then the integer is negative, if not then positive.

这篇关于哈希码是内存地址还是内存地址内容的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆