ITeye博客

Java String中的hashCode函数

liu0107613 · 2009-06-27 09:43 · java · 编程语言 · C · 算法 · Java · 编程 · JDK · Markdown

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 < 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

 

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 < str.length(); i++)
      {
         hash = (hash * seed) + str.charAt(i);
      }

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

 

参考路径:http://www.partow.net/programming/hashfunctions/index.html

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。