I'm supposed to create a hash table that applies a hash function to a first and last name (key) and lookup the appropriate index. The telephone number (value) should be returned on doing a lookup. Although I'm really asking for help with my hash function, which is terribly incorrect, if someone could rewrite the method in their own way, I'd gladly appreciate it. I'm just confused on how to make a hash function that returns an index upon doing a calculation on a string. If someone would please take the time to read over this code, you would be a tremendous help. Thank You.
P.S: My hash function method is named 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;
}
}