我应该创建一个哈希表,将哈希函数应用于名字和姓氏(键)并查找相应的索引。执行查找时应返回电话号码(值)。虽然我真的在寻求帮助我的哈希函数,这是非常不正确的,如果有人可以用自己的方式重写方法,我很乐意欣赏它。我只是对如何创建一个在对字符串进行计算时返回索引的哈希函数感到困惑。如果有人愿意花时间阅读这段代码,那将是一个巨大的帮助。谢谢。
P.S:我的哈希函数方法名为hashFunction(String key)
import java.util.Scanner;
/*
* The following class implements a telephone directory search using Hash Tables
*/
public class HashTableImplementation{
public static void main(String[] args){
HashTable directory = new HashTable();
System.out.println("\tWelcome to the Telephone Directory");
System.out.println("The following directory is pre-populated with 20 people");
directory.setTableSize();
directory.insert("John", "7777");
System.out.print(directory.getTableKey());
}
}
class LinkListNode{
private LinkListNode link;
private String data;
/*\
* Constructor sets top to null value and counter to 0.
*/
public LinkListNode(String data){
link = null;
this.data = data;
}
}
/*
* The following class provides methods for hash table implementation
*/
class HashTable {
private String key;
private String phoneNum;
private final int TABLE_SIZE = 20;
private HashTable[] table;
/*
* Default constructor
*/
public HashTable(){
}
public HashTable(String key, String value) {
this.key = key;
this.phoneNum = value;
}
/*
* Setting table size implements empty hash-table
*/
public void setTableSize(){
table = new HashTable[TABLE_SIZE];
for(int i = 0; i < TABLE_SIZE; i++){
table[i] = null;
}
}
/*
* Returns phone number of person in directory
*/
public String getTableValue(int key){
int hash = (key % TABLE_SIZE);
while((table[hash] != null) && (!table[hash].getKey().equals(key)) ){
hash = hash++ % TABLE_SIZE;
}
if(table[hash] == null){
return null;
}
else{
return table[hash].getValue();
}
}
/*
* Returns firstName and lastName of person in directory
*/
public String getTableKey(String key){
int index = hashFunction(key);
if(table[index] == null){
return null;
}
return table[index].getKey();
}
/*
* Function to insert a key-value pair into the hash table
*/
public void insert(String key, String value){
int index = hashFunction(key);
table[index] = new HashTable(key, value);
}
public int hashFunction(String key) {
int sum = 0;
int nameLength = table.length;
for(int i = 0; i < nameLength; i++){
sum += (int)key.charAt(i);
}
return sum % TABLE_SIZE;
}
/*
* Gets firstName and lastName
*/
public String getKey(){
return key;
}
/*
* Gets phone number
*/
public String getValue() {
return phoneNum;
}
/*
* Returns hash-table size
*/
public int getSize(){
return TABLE_SIZE;
}
public String toString(){
String string;
string = "" + key;
return string;
}
}