String的hashCode分析
2024-08-27 02:11:35
/**
* Returns a hash code for this string. The hash code for a
* {@code String} object is computed as
* <blockquote><pre>
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
* </pre></blockquote>
* using {@code int} arithmetic, where {@code s[i]} is the
* <i>i</i>th character of the string, {@code n} is the length of
* the string, and {@code ^} indicates exponentiation.
* (The hash value of the empty string is zero.)
*
* @return a hash code value for this object.
*/
private int hash;
private char[] value;
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
上面是hashCode源码,源码英文翻译就是,调用这个方法返回一个int值。空字符串的hashCode为0。hash值主要用来比较String是否equals,但不一定 ==。
至于为什么用31去构造算法,从数学上,31质数可以在JVM中很好的分配hashCode,如果数字相乘过大会导致溢出,从而导致数据的丢失。
最新文章
- iOS之隐藏键盘的方式
- css margin
- 51nod 1422(强行YY)
- 无废话Android之activity的生命周期、activity的启动模式、activity横竖屏切换的生命周期、开启新的activity获取他的返回值、利用广播实现ip拨号、短信接收广播、短信监听器(6)
- hdu 1114 Piggy-Bank
- Prim算法和Kruskal算法(图论中的最小生成树算法)
- 判断浏览器是IE的几种方式
- What is the difference between database table and database view?
- NSArrary和NSString间的转换
- OpenSessionInViewFilter与org.springframework.dao.InvalidDataAccessApiUsageException
- 生成器模式(Builder)
- 2013 多校联合 2 A Balls Rearrangement (hdu 4611)
- Jenkins email-ext邮件通知模板
- 多校 Robot Motion
- C# App.config配置文件的讲解
- 解决Java getResource 路径中含有中文的情况
- 【C#】list 去重(转载)
- 初步了解three.js
- 15:CSS3 3D
- [转]启动Tomcat提示:指定的服务未安装