Attempting to better understand chaining on a hashtable. Seeking a simple table that hashes a value and only associates one integer to the value hashed. Here is sample code of the problem in question...
/* hash string value return int */
public int hashFunction(String D) {
char[] Thing = D.toCharArray();
for(int i=0; i < Thing.length; i++){
index += Thing[i]; }
return index % TABLE_SIZE;
}
/* hash string value return void */
public void hashFunction(String D) {
char[] Thing = D.toCharArray();
for(int i=0; i < Thing.length; i++){
index += Thing[i];}
int hash = index % TABLE_SIZE;
if(table[hash] == null){
table[hash] = new HashEntry( Level, Value );
}
else{
table[hash].setNext(nd);
}
}
/* miscellaneous code snippet */
if(table[hash] == null){
table[hash] = new HashEntry();
}
else if (Data.compareTo("VAR") == 0) {
Data = inFile.next();
char[] Thing = Data.toCharArray();
for(int i=0; i < Thing.length; i++){
hash += Thing[i];}
hash = hash % TABLE_SIZE;
hm.setIntoHashTable(hash);
Data = inFile.next();
if(Data.compareTo("=") == 0) {
Data = inFile.next();
int value = Integer.parseInt(Data);
hm.getIntoHashTable(he.setValue(value));
}
}
Well the chaining occurs when you have collision in the indexes.
Lets assume you have a TABLE_SIZE=10
Now you have to store string abc
, so you get hash as 4
Now when you gonna store string cba
, you end up with same hash 4
So now to store cba
at the same index, you will create and store a List at index 4
.
The List will contain both abc
and bca
. This List is called chain
and this process of storing multiple values at the same hash is called Chaining
.
Pseudo code look like:
if(table[hash] == null)
table[hash] = new ArrayList<HashEntry>();//APPEND ON TO THE LOCATION ALREADY THERE!
table[hash].add(new HashEntry());
The table will be declared as:
@SuppressWarnings("unchecked")
List<HashEntry>[] table = new List[TABLE_SIZE];
You might have to suppress warning as arrays and generics dont go smoothly.