我正在编写自己的hashmap实现,我正在使用horner规则作为散列算法。我这里有我的哈希算法
public int hashCode(K key) {
int rank = 0;
int hashCode = 0;
char[] charArr = ((String) key).toCharArray();
int exponent = (5 * (charArr.length - 1)) - 5;
for(int i = 0; i <= charArr.length - 1; i++) {
if(exponent >= 0) {
rank = ((int) charArr[i] - 'A') + 1;
hashCode += rank * (32 << exponent);
exponent -= 5;
}
else{
rank = ((int) charArr[i] - 'A') + 1;
hashCode += rank * (32 >> 5);
}
}
return hashCode;
}
如果给的话 String userStr = "tea"
它将产生20641作为开始的哈希值。我之所以知道这一点,是因为在我取出的方法中,打印用于故障排除的语句。不过,当我稍后在驱动程序中接收哈希值时,会得到54465作为值。这不是双20641,所以它不只是运行两次。我不知道为什么会这样。我将检索方法附加到 HashTable class
,以及遇到问题的驱动程序部分。提前感谢您的帮助。
public V tableRetrieve(K searchKey) {
if(!this.tableIsEmpty()) {
int index = hashCode(searchKey) % table.length;
ChainNode<K, V> currNode = table[index]; //getting the node based off the index
while(currNode != null) {
if(currNode.getKey().equals(searchKey)) {
return currNode.getValue(); //found match return currNode value
}
else {
currNode = currNode.getNext(); //go onto next node within linked list
}
}
}
return null; //if nothing was found return null
}
public static void retrieveHashCode(HashTable<String, Integer> myTable) {
try {
String key;
System.out.print("Please enter a string key to retrieve the hashcode of it from the table\n> ");
key = input.readLine();
if(myTable.tableRetrieve(key.toUpperCase()) != null) {
System.out.println("The hash code of " + key + " is " + myTable.hashCode(key) + ".");
}
else {
System.out.println("The key " + key + " is not present within the table.");
}
}
catch(InputMismatchException e) {
System.out.println("Please enter a string value.");
}
catch(IOException e1) {
System.out.println(e1.getMessage());
}
}
暂无答案!
目前还没有任何答案,快来回答吧!