String字符串散列函数
package com.maple.hash;
/**
* string hash function
*
* @author RhymeChiang
* @date 2018/01/31
**/
public class StringHashFunction {
/**
* string hash function
* 该散列函数的特点是如果关键字特别长,计算起来将会花费过多的时间
* 这个时候采用的策略为不使用所有的字符。
* 可以选择特定的字符参与散列运算
*
* @param key
* @param tableSize
* @return
*/
public static int hash(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;
}
}