---
title: "String源码中hashCode算法"
author: "TimerBin"
date: "2016-03-01T11:17:10Z"
tags: []
categories: ["编程语言"]
slug: "string-hashcode"
draft: false
lastmod: "2016-03-01T11:17:10Z"
id: 2279685
url: "https://timerbin.iteye.com/blog/2279685"
---

针对java中String源码hashcode算法源码分析

 

```
/** The value is used for character storage. */
private final char value[];  //将字符串截成的字符数组

/** Cache the hash code for the string */
private int hash; // Default to 0 用以缓存计算出的hashcode值

/**
  * Returns a hash code for this string. The hash code for a
  * <code>String</code> object is computed as
  * <blockquote><pre>
  * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
  * </pre></blockquote>
  * using <code>int</code> arithmetic, where <code>s[i]</code> is the
  * <i>i</i>th character of the string, <code>n</code> is the length of
  * the string, and <code>^</code> indicates exponentiation.
  * (The hash value of the empty string is zero.)
  *
  * @return  a hash code value for this object.
  */
  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;
    }
```

 按照上面源码举例说明：

 

String msg = "abcd";  // 此时value\[] = {'a','b','c','d'}  因此

for循环会执行4次

第一次：h = 31\*0 + a = 97 

第二次：h = 31\*97 + b = 3105 

第三次：h = 31\*3105 + c = 96354 

第四次：h = 31\*96354 + d = 2987074 

由以上代码计算可以算出 msg 的hashcode = 2987074  刚好与 System.err.println(new String("abcd").hashCode()); 进行验证

 

在源码的hashcode的注释中还提供了一个多项式计算方式：

s\[0]\*31^(n-1) + s\[1]\*31^(n-2) + ... + s\[n-1]      

s\[0] ：表示字符串中指定下标的字符

n：表示字符串中字符长度

a\*31^3 + b\*31^2 + c\*31^1 + d = 2987074  + 94178 + 3069 + 100 = 2987074 ;