javascript 实现 java 中String的hashcode方法

来源:互联网 发布:json查看 编辑:程序博客网 时间:2024/04/24 21:10

转自:http://zhhphappy.iteye.com/blog/1124283

javascript中有需要用到像类似java中的hashcode方法,想把java中的hashcode方法直接搬到js中发现不行

Java代码  收藏代码
  1. /** 
  2.      * Returns a hash code for this string. The hash code for a 
  3.      * <code>String</code> object is computed as 
  4.      * <blockquote><pre> 
  5.      * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] 
  6.      * </pre></blockquote> 
  7.      * using <code>int</code> arithmetic, where <code>s[i]</code> is the 
  8.      * <i>i</i>th character of the string, <code>n</code> is the length of 
  9.      * the string, and <code>^</code> indicates exponentiation. 
  10.      * (The hash value of the empty string is zero.) 
  11.      * 
  12.      * @return  a hash code value for this object. 
  13.      */  
  14.     public int hashCode() {  
  15.     int h = hash;  
  16.         int len = count;  
  17.     if (h == 0 && len > 0) {  
  18.         int off = offset;  
  19.         char val[] = value;  
  20.   
  21.             for (int i = 0; i < len; i++) {  
  22.                 h = 31*h + val[off++];  
  23.             }  
  24.             hash = h;  
  25.         }  
  26.         return h;  
  27.     }  

 关键是hash的类型是int,int的范围是MIN_VALUE = 0x80000000; MAX_VALUE = 0x7fffffff;

这样在执行

Java代码  收藏代码
  1. h = 31*h + val[off++];  

 的时候当超有可能超过int的最大值,变成负数。但js里面是不区分int,long的直接显示,显示不下用科学技术法,所以需要一个模拟java中int超出范围变负数的方法。

最终的实现如下:

Js代码  收藏代码
  1. function isNull(str){  
  2.         return str == null || str.value == "";  
  3.     }  
  4.       
  5.     /** 
  6.      * java String hashCode 的实现 
  7.      * @param strKey 
  8.      * @return intValue 
  9.      */  
  10.     function hashCode(strKey)  
  11.     {  
  12.         var hash = 0;  
  13.         if(!isNull(strKey))  
  14.         {  
  15.             for (var i = 0; i < strKey.length; i++)  
  16.             {  
  17.                 hash = hash * 31 + strKey.charCodeAt(i);  
  18.                 hash = intValue(hash);  
  19.             }  
  20.         }  
  21.         return hash;  
  22.     }  
  23.   
  24.     /** 
  25.      * 将js页面的number类型转换为java的int类型 
  26.      * @param num 
  27.      * @return intValue 
  28.      */  
  29.     function intValue(num)  
  30.     {  
  31.         var MAX_VALUE = 0x7fffffff;  
  32.         var MIN_VALUE = -0x80000000;  
  33.         if(num > MAX_VALUE || num < MIN_VALUE)  
  34.         {  
  35.             return num &= 0xFFFFFFFF;  
  36.         }  
  37.         return num;  
  38.     }  
  39. /** * 得到分片号 * @param strKey * @return intValue */function getShard(strKey){    var shardNum=8;    var index=hashCode(strKey)%shardNum;    if(index<0)        index+=shardNum;    return index;}

0 0
原创粉丝点击