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;
}
分享到:
相关推荐
如何正确实现Java中的HashCode共6页.pdf.zip
主要给大家介绍了关于Java中HashCode方法的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Java具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
在java中一个hashCode算法,可以用来计算一个字符串的hash值,今天一个朋友突然问俺能不能在js中计算hashCode,要求和java的hashCode计算结果一样。 对于java的hashCode,以前到现在也一直没有了解过其算法,不过...
实际上,hashcode根本不能代表object的内存地址。
本篇文章主要介绍了Java中的hashcode方法,详细的介绍了hashCode方法的作用,具有一定的参考价值,有需要的可以了解一下。
哈希表这个数据结构想必大多数人都不陌生,而且在很多地方都会利用到hash表来提高查找效率。在Java的Object类中有一个方法: public native int hashCode();...在Java中也一样,hashCode方法的主要作用是为了配合基于
哈希生成器js 一个Vue.js应用程序,其中包含Java中String类的hashCode方法的javascript实现构建设置# install dependenciesnpm install# serve with hot reload at localhost:8080npm run dev# build for production...
安装npm install string-hashcode 例子var hashCode = require ( 'string-hashcode' ) ;var s = 'abc' ;console . log ( s . hashCode ) ; // undefinedvar code = hashCode ( s ) ;console . log ( s . hashCode ) ...
主要介绍了深入理解Java中HashCode方法,具有一定借鉴价值,需要的朋友可以参考下
Java equals 方法与hashcode 方法的深入解析.rar
java中Hashcode的作用
深入 HashCode 方法~~~~~
主要介绍了Java中的hashcode方法介绍,还是比较不错的,这里分享给大家,供需要的朋友参考。
更清楚的了解hashcode()和equals()方法。
主要介绍了java中的hashCode方法小例子,有需要的朋友可以参考一下
Java重写equals同时需要重写hashCode的代码说明,以及如何重写hashCode方法,此代码演示按照effective java书籍说明的重写思路。代码中演示了使用集合存储对象,并且对象作为key,需重写equals和hashCode.
主要介绍了java 中HashCode重复的可能性的相关资料,这里提供实例及测试代码,需要的朋友可以参考下