Created
July 23, 2011 22:07
-
-
Save anupsavvy/1101939 to your computer and use it in GitHub Desktop.
Simple Hashtable with linear probing in java ( Does not apply any growth strategy).
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
public class Hashtable{ | |
private static final int SIZE = 97; | |
private Pair[] map = null; | |
public Hashtable(){ | |
this(SIZE); | |
} | |
public Hashtable(int N){ | |
map = new Pair[N]; | |
for(int i =0; i < N ; i++){ | |
map[i]=null; | |
} | |
} | |
public void put(int key, int value) throws HashtableException { | |
int hash = key % SIZE; | |
int count = 0; | |
while(map[hash] != null && map[hash].getKey() != key){ | |
hash = (hash + 1) % SIZE; | |
if(count == SIZE) | |
throw new HashtableException("Table full"); | |
count++; | |
} | |
map[hash]= new Pair(key,value); | |
} | |
public int get(int key) throws HashtableException{ | |
int hash = key % SIZE; | |
int count = 0; | |
while(map[hash] != null && map[hash].getKey() != key){ | |
hash = (hash+1) % SIZE; | |
if(count == SIZE) | |
throw new HashtableException("No matching key in the table"); | |
count++; | |
} | |
if(map[hash] == null) | |
throw new HashtableException("No matching key in the table"); | |
return map[hash].getValue(); | |
} | |
} | |
class Pair{ | |
private int key; | |
private int value; | |
public Pair(int key, int value){ | |
this.key = key; | |
this.value = value; | |
} | |
public int getKey(){ | |
return key; | |
} | |
public int getValue(){ | |
return value; | |
} | |
} | |
class HashtableException extends RuntimeException{ | |
public HashtableException(String message){ | |
super(message); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment