Created
April 12, 2017 18:57
-
-
Save honux77/11c105933f5990ce97af15e905f8b954 to your computer and use it in GitHub Desktop.
Simple Hash Implementation (Linear Proving)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package honux; | |
/** | |
* Simple Hash implementation | |
* It can't expand and no exception handling for put! | |
* | |
* @author honux | |
* | |
*/ | |
public class MyHash { | |
private final static int TABLE_SIZE = 128; | |
private int count = 0; | |
HashEntry[] table; | |
public MyHash() { | |
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); | |
while (table[hash] != null && table[hash].getKey() != key) | |
hash = (hash + 1) % TABLE_SIZE; | |
if (table[hash] == null) | |
return -1; | |
else | |
return table[hash].getValue(); | |
} | |
public void put(int key, int value) { | |
int hash = (key % TABLE_SIZE); | |
while (table[hash] != null && table[hash].getKey() != key) | |
hash = (hash + 1) % TABLE_SIZE; | |
table[hash] = new HashEntry(key, value); | |
count++; | |
} | |
} | |
class HashEntry { | |
private int key; | |
private int value; | |
public HashEntry(int key, int value) { | |
this.key = key; | |
this.value = value; | |
} | |
public int getKey() { | |
return key; | |
} | |
public int getValue() { | |
return value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment