Why does Java's hashCode() in String use 31 as a multiplier?
In Java, 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.
Why is 31 used as a multiplier?
I understand that the multiplier should be a relatively large prime number. So why not 29, or 37, or even 97?
Answers:
According to Joshua Bloch's Effective Java (a book that can't be recommended enough, and which I bought thanks to continual mentions on stackoverflow):
The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed, information would be lost, as multiplication by 2 is equivalent to shifting. The advantage of using a prime is less clear, but it is traditional. A nice property of 31 is that the multiplication can be replaced by a shift and a subtraction for better performance: 31 * i == (i << 5) - i. Modern VMs do this sort of optimization automatically.
(from Chapter 3, Item 9: Always override hashcode when you override equals, page 48)
URL: http://stackoverflow.com/questions/299304/why-does-javas-hashcode-in-string-use-31-as-a-multiplier
分享到:
相关推荐
java中Hashcode的作用
安装npm install string-hashcode 例子var hashCode = require ( 'string-hashcode' ) ;var s = 'abc' ;console . log ( s . hashCode ) ; // undefinedvar code = hashCode ( s ) ;console . log ( s . hashCode ) ...
实际上,hashcode根本不能代表object的内存地址。
Java重写equals同时需要重写hashCode的代码说明,以及如何重写hashCode方法,此代码演示按照effective java书籍说明的重写思路。代码中演示了使用集合存储对象,并且对象作为key,需重写equals和hashCode.
主要给大家介绍了关于Java中HashCode方法的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Java具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
主要介绍了java 中HashCode重复的可能性的相关资料,这里提供实例及测试代码,需要的朋友可以参考下
NULL 博文链接:https://songjianyong.iteye.com/blog/1676894
Java基础加强_ArrayList_HashSet的比较及Hashcode分析
java中hashcode和equals的详解.pdf
在java中一个hashCode算法,可以用来计算一个字符串的hash值,今天一个朋友突然问俺能不能在js中计算hashCode,要求和java的hashCode计算结果一样。 对于java的hashCode,以前到现在也一直没有了解过其算法,不过...
NULL 博文链接:https://zpointer.iteye.com/blog/1058337
有许多人学了很长时间的Java,但一直不明白hashCode方法的作用以及equals()和==的区别,我来解释一下吧。首先,想要明白hashCode的作用,你必须要先知道Java中的集合。总的来说,Java中的集合(Collection)有两类,...
以下是关于HashCode的官方文档定义: hashcode方法返回该对象的哈希码值。支持该方法是为哈希表提供一些优点,例如,java.util.Hashtable 提供的哈希表。 hashCode 的常规协定是: 在Java应用程序执行期间...
总结非常完全的文档。对Java初学着和进阶学习的学者是一份相当不错的Java学习资料
java中hashcode()和equals()的详解.docx
主要介绍了深入理解Java中HashCode方法,具有一定借鉴价值,需要的朋友可以参考下
主要介绍了Java 中HashCode作用以及hashcode对于一个对象的重要性,对java中hashcode的作用相关知识感兴趣的朋友一起学习吧
更清楚的了解hashcode()和equals()方法。