Implementation of a hash function in java, haven't got round to dealing with collisions yet. I tried to use good code, refactored, descriptive variable names, nice syntax.
My code must be efficient and extensible.
Would be interested to know how you guys would improve. Three classes:
- TestHash - main method is here, hash is initialised and data inserted and read
- HashTable -object were the hash table is held
- HashEntry - each entry in the array is a 'HashEntry' object
HashTable
import java.io.*;
public class HashTable {
// number of indexes in hash table
private final static int TABLE_SIZE = 100;
// initialise array of HashEntry (table)
HashEntry[] table;
// constructor, create array, assign all values to null
HashTable() {
// create array of HashEntry, predefined size
table = new HashEntry[TABLE_SIZE];
// assign all values to null
for (int i = 0; i < TABLE_SIZE; i++) {
table[i] = null;
}
}
// from key, find the correct index, load the HashEntry object and return the value
public String getValue(String key) {
int index = this.getKeyIndex(key);
HashEntry chosen_entry = table[index];
String chosen_entry_value = chosen_entry.getValue(key);
return chosen_entry_value;
}
// creates a new HashEntry object, inserts that into the table array at the correct index
// determined by getKeyIndex(key)
public void insert(String key, String value) {
int index = this.getKeyIndex(key);
HashEntry keyValuePair;
keyValuePair = new HashEntry(key, value);
table[index] = keyValuePair;
return;
}
// ** PRIVATE FUNCTIONS ** //
// get index from key
private Integer getKeyIndex(String key) {
int hash = 7;
for (int i = 0; i < key.length(); i++) {
hash = (hash*31 + key.charAt(i))%100;
}
return hash;
}
}
HashEntry
public class HashEntry {
private String key;
private String value;
HashEntry(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return this.key;
}
public String getValue(String key) {
// use string key to move down linked list in case of collision
// haven't implemented this yet
return this.value;
}
}
TestHash
public class TestHash {
public static void main(String[] args)
{
HashTable tableHash = new HashTable();
tableHash.insert("david", "england");
tableHash.insert("joe", "united states");
tableHash.insert("maria", "china");
System.out.println(tableHash.getValue("joe"));
}
}