javascript 实现 java 中String的hashcode方法
来源:互联网 发布:json查看 编辑:程序博客网 时间:2024/04/24 21:10
转自:http://zhhphappy.iteye.com/blog/1124283
javascript中有需要用到像类似java中的hashcode方法,想把java中的hashcode方法直接搬到js中发现不行
- /**
- * 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;
- int len = count;
- if (h == 0 && len > 0) {
- int off = offset;
- char val[] = value;
- for (int i = 0; i < len; i++) {
- h = 31*h + val[off++];
- }
- hash = h;
- }
- return h;
- }
关键是hash的类型是int,int的范围是MIN_VALUE = 0x80000000; MAX_VALUE = 0x7fffffff;
这样在执行
- h = 31*h + val[off++];
的时候当超有可能超过int的最大值,变成负数。但js里面是不区分int,long的直接显示,显示不下用科学技术法,所以需要一个模拟java中int超出范围变负数的方法。
最终的实现如下:
- function isNull(str){
- return str == null || str.value == "";
- }
- /**
- * java String hashCode 的实现
- * @param strKey
- * @return intValue
- */
- function hashCode(strKey)
- {
- var hash = 0;
- if(!isNull(strKey))
- {
- for (var i = 0; i < strKey.length; i++)
- {
- hash = hash * 31 + strKey.charCodeAt(i);
- hash = intValue(hash);
- }
- }
- return hash;
- }
- /**
- * 将js页面的number类型转换为java的int类型
- * @param num
- * @return intValue
- */
- function intValue(num)
- {
- var MAX_VALUE = 0x7fffffff;
- var MIN_VALUE = -0x80000000;
- if(num > MAX_VALUE || num < MIN_VALUE)
- {
- return num &= 0xFFFFFFFF;
- }
- return num;
- }
/** * 得到分片号 * @param strKey * @return intValue */function getShard(strKey){ var shardNum=8; var index=hashCode(strKey)%shardNum; if(index<0) index+=shardNum; return index;}
0 0
- javascript 实现 java 中String的hashcode方法
- java中String类的hashCode方法实现
- JAVA中String类的hashCode方法
- Java中String类的hashCode方法
- String的hashCode方法实现
- Java String的hashCode实现
- 用php实现java的String的hashCode方法
- 关于Java中String类的hashCode方法
- 关于Java中String类的hashCode方法
- Java中Object对象的hashCode方法和String对象的hashCode
- String中hashCode方法
- Java 中String的HashCode计算方法
- java string的hashcode
- String的hashcode(java)
- String的hashcode(java)
- java.lang.String hashCode方法
- [Java--基础]----String hashCode实现
- Java编程:String 类中 hashCode() 方法详解
- JOS大内核锁
- 声光控延时开关设计原理
- CodeForces 592C (胡搞)
- jieba分词
- 如何防止滴滴出行后台自启
- javascript 实现 java 中String的hashcode方法
- Fundation中常用结构体
- 你可能不再需要Underscore
- 命令行选择
- log4j配置
- 使用Java爬虫得到CSDN博客信息并保存(一)
- 算数-分数和小数
- Eclipse设置字体大小
- 使用Java爬虫得到CSDN博客信息并保存(一)