patternjavaMinor
Hash function for strings
Viewed 0 times
stringsfunctionforhash
Problem
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:
inserted and read
HashTable
HashEntry
```
public class HashEnt
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 HashEnt
Solution
Very nifty-looking code right there. However, you should declare
omitting the
table as private final. Also, you don't need to initialize each array component of table to null, Java already does this for you. What comes to insert, you could write simplytable[index] = new HashEntry(key, value);omitting the
return statement. Point is to write only necessary statements. In getValue, you might want to check whether table[index] is null, since if that is the case, your implementation will throw NullPointerException.Code Snippets
table[index] = new HashEntry(key, value);Context
StackExchange Code Review Q#111409, answer score: 3
Revisions (0)
No revisions yet.