先看看string的默认hash方法,代码如下
/**
* Returns a hash code for this string. The hash code for a
* {@code String} object is computed as
* <blockquote><pre>
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
* </pre></blockquote>
* using {@code int} arithmetic, where {@code s[i]} is the
* <i>i</i>th character of the string, {@code n} is the length of
* the string, and {@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;//default 0
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
此hash算法实现上是循环原哈希值×31再加下一个Char的值,Eclipse的自动代码生成的hashCode()函数也是类似的,循环原哈希值×31,再加下一个属性的hashCode()值。代码如下:
@Override
public int hashCode() {
int result = idNo != null ? idNo.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (userId != null ? userId.hashCode() : 0);
result = 31 * result + (channelFlag != null ? channelFlag.hashCode() : 0);
return result;
}
此处不太明白下一个char的值,那么我们测试一下,看看
public class Test {
public static void main(String[] args){
char[] chars={'我','的'};
int i=chars[0];
int j=chars[1];
System.out.println(i);
System.out.print(j);
}
}
输出结果如下:
25105
30340
public static void main(String[] args){
char[] chars={'2','的'};
int i=chars[0]-'0';
int j=chars[1];
System.out.println(i);
System.out.print(j);
}
输出结果如下:
2
30340
第一个结果的int是char的ascii值,第二个例子,我们期待如果不输出ascii值,怎么处理,其具体原理稍后研究。
主要采用horner法则,解释如下: