/**
* 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,如果数字相乘过大会导致溢出,从而导致数据的丢失。

最新文章

  1. iOS之隐藏键盘的方式
  2. css margin
  3. 51nod 1422(强行YY)
  4. 无废话Android之activity的生命周期、activity的启动模式、activity横竖屏切换的生命周期、开启新的activity获取他的返回值、利用广播实现ip拨号、短信接收广播、短信监听器(6)
  5. hdu 1114 Piggy-Bank
  6. Prim算法和Kruskal算法(图论中的最小生成树算法)
  7. 判断浏览器是IE的几种方式
  8. What is the difference between database table and database view?
  9. NSArrary和NSString间的转换
  10. OpenSessionInViewFilter与org.springframework.dao.InvalidDataAccessApiUsageException
  11. 生成器模式(Builder)
  12. 2013 多校联合 2 A Balls Rearrangement (hdu 4611)
  13. Jenkins email-ext邮件通知模板
  14. 多校 Robot Motion
  15. C# App.config配置文件的讲解
  16. 解决Java getResource 路径中含有中文的情况
  17. 【C#】list 去重(转载)
  18. 初步了解three.js
  19. 15:CSS3 3D
  20. [转]启动Tomcat提示:指定的服务未安装

热门文章

  1. centos上tensorflow一键安装脚本
  2. 51Nod 1305 Pairwise Sum and Divide | 思维 数学
  3. 数据结构:Bitset
  4. 【C++对象模型】第三章 Data语义学
  5. CSS浮动为什么不会遮盖同级元素
  6. js刷新页面方法 -- (转)
  7. cuda中的二分查找
  8. [Leetcode Week16]Insertion Sort List
  9. GDB实战
  10. 测试mysqldump 压缩率和时间消耗