java哈希码地址,哈希码是内存地址还是内存地址内容的整数?

Why does this code give a negative 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());

}

}

解决方案

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:

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.)

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值