---
title: "Java String中的hashCode函数"
author: "liu0107613"
date: "2009-06-27T09:43:51Z"
tags: ["C", "JDK", "Java", "算法", "编程"]
categories: ["编程语言"]
slug: "java-string-hashcode"
draft: false
lastmod: "2009-06-27T09:43:51Z"
id: 415941
url: "https://liu0107613.iteye.com/blog/415941"
---

String 类中的hash函数如下：

    public int hashCode() {  
 int h = hash;  
 if (h == 0) {  
     int off = offset;  
     char val\[] = value;  
     int len = count;

            for (int i = 0; i &lt; len; i++) {  
                h = 31\*h + val\[off++];  
            }  
            hash = h;  
        }  
        return h;  
    }

 

 

具体的计算公式是：s\[0]\*31^(n-1) + s\[1]\*31^(n-2) + ... + s\[n-1]

 

 

上面的代码可见简洁和高效。JDK的源代码。

 

这个hash算法的名称叫：[**BKDR Hash Function**](http://liu0107613.iteye.com/admin/blogs/#top)

 

This hash function comes from Brian Kernighan and Dennis Ritchie's book "The C Programming Language". It is a simple hash function using a strange set of possible seeds which all constitute a pattern of 31....31...31 etc, it seems to be very similar to the DJB hash function.

 

算法来自于Brian Kernighan and Dennis Ritchie合著的C语言编程一书。函数用一个特殊的种子集合构建哈希函数

 

该算法代码：

   public long BKDRHash(String str)  
   {  
      long seed = 131; // 31 131 1313 13131 131313 etc..  
      long hash = 0;

      for(int i = 0; i &lt; str.length(); i++)  
      {  
         hash = (hash * seed) + str.charAt(i);  
      }

      return hash;  
   }  
   /* End Of BKDR Hash Function \*/

 

参考路径：[http://www.partow.net/programming/hashfunctions/index.html](http://www.partow.net/programming/hashfunctions/index.html)