java string 计算原理 code
public int hashCode() { int i = this.hash; if ((i == 0) && (this.value.length > 0)) { char[] arrayOfChar = this.value; for (int j = 0; j < this.value.length; ++j) i = 31 * i + arrayOfChar[j]; this.hash = i; } return i; }
java 测试code
public class test_hashcode { public static void main(String args[]) { String Str = new String("www.runoob.com"); System.out.println(Str+" ,字符串的哈希码为 :" + Str.hashCode() ); char a_ ; a_ = 'a'; int res ; res = 1+ a_ System.out.println("1+a :" + res ); } }
awk code
awk -f ./hashcode_test.awk
hashcode_test.awk
BEGIN { for (ii = 0; ii < 256; ++ii) { ch = sprintf("%c", ii); ascii[ch] = ii; } h = 0 ; strings="www.runoob.com" if(h ==0 && length(strings)>0) { for (i=1;i<= length(strings) ; ++i) { j=ascii[substr(strings,i,1)] print h " * 31 +" j |& "bc" "bc" |& getline var2 #h=31*h+j h=var2 } } print "(" h " +2147483648)%4294967296-2147483648 " |& "bc" "bc" |& getline Result print strings " , hashcode " Result }
实现结果
awk 结果
java 结果
oracle 函数实现 ,验证就不贴了
CREATE OR REPLACE FUNCTION HASHCODE(STR IN VARCHAR2) RETURN INTEGER IS RESULT INTEGER := 0; BEGIN FOR I IN 1 .. LENGTH(STR) LOOP RESULT := 31 * RESULT + ASCII(SUBSTR(STR, I, 1)); END LOOP; RESULT := MOD((RESULT + 2147483648), 4294967296) - 2147483648; RETURN(RESULT); END HASHCODE;
awk function
function hashcode(strings) { for (ii = 0; ii < 256; ++ii) { ch = sprintf("%c", ii); ascii[ch] = ii; } h = 0 ; if(h ==0 && length(strings)>0) { for (i=1;i<= length(strings) ; ++i) { j=ascii[substr(strings,i,1)] print h " * 31 +" j |& "bc" "bc" |& getline var2 h=var2 #print i","substr(strings,i,1) " , " j" , " h } } print "(" h " +2147483648)%4294967296-2147483648 " |& "bc" "bc" |& getline Result #print strings " , hashcode " Result return Result } ## test hashcode BEGIN { a ="www.runoob.com" Hcode= hashcode(a) print a " , hashcode " Hcode }