Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Last active August 29, 2015 14:12
Show Gist options
  • Save dmnugent80/59333f7eae8a7665c073 to your computer and use it in GitHub Desktop.
Save dmnugent80/59333f7eae8a7665c073 to your computer and use it in GitHub Desktop.
HashTable with Chaining
//Used this example as a template: http://www.algolist.net/Data_structures/Hash_table/Simple_example
/*
*HashEntry class
*/
public class HashEntry {
public HashEntry next;
private int key;
private int value;
HashEntry(int key, int value) {
this.key = key;
this.value = value;
this.next = null;
}
public int getKey() {
return key;
}
public int getValue() {
return value;
}
}
/*
*HashMap class
*/
public class HashMap {
private final static int TABLE_SIZE = 128;
HashEntry[] table;
HashMap() {
table = new HashEntry[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++)
table[i] = null;
}
public int get(int key) {
int hash = (key % TABLE_SIZE);
if (table[hash] == null)
return -1;
if (table[hash].getKey() == key){
return table[hash].getValue();
}
else{
//traverse list of collisions to search for key
HashEntry curr = table[hash].next;
while (curr != null){
if (curr.getKey() == key){
return curr.getValue();
}
curr = curr.next;
}
}
return -1;
}
public void put(int key, int value) {
int hash = (key % TABLE_SIZE);
if (table[hash] == null){
table[hash] = new HashEntry(key, value);
}
else{
//collision occurred, traverse list until end, and add key/value pair if they do not already exist
HashEntry curr = table[hash];
while (true){
if (curr.getKey() == key && curr.getValue() == value){
//key/value combination already exists, exit function
return;
}
else if (curr.next == null){
curr.next = new HashEntry(key, value);
return;
}
curr = curr.next;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment