package com.abstractdatatype.hash;
/*把字符串中字符的ASCII码(或Unicode码)值加起来*/
public class HashMethod {
public static void main(String[] args) {
int length=HashMethod.hash("admin", 3);
int size=HashMethod.hash_better("admin", 3);
System.out.println(size);
System.out.println(length);
System.out.println("admin".hashCode()%3);
}
//一个简单的散列函数
public static int hash(String key,int tableSize){
int hashVal=0;
for(int i=0;i<key.length();i++){
hashVal=key.charAt(i)+hashVal; //key.charAt(i)返回的是个一char,当与一个数字相加时,这个char就会自动转为int型的
}
//这里面 hashVal就和key.hashCode是等价的
return hashVal%tableSize;//hashVal与tableSize取模可以得到hashcode
}
//一个好的散列函数
public static int hash_better(String key,int tableSize){
int hashVal=0;
for(int i=0;i<key.length();i++){
hashVal=37*hashVal+key.charAt(i);
hashVal%=tableSize;
if(hashVal<0){
hashVal+=tableSize;
}
}
return hashVal;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return super.hashCode();
}
}
hash函数
最新推荐文章于 2021-04-09 07:45:54 发布