Possible Duplicate:
The fundamentals of Hash tables?
I am trying to implement a Simple Hash Table probably with simple java arrays. But 1st I will need to somehow have an associative array or sorts? How might a simple Hash Table implementation look like? It should still be able to do add/delete/get in O(1)
A hash table basically takes an input key, hashes it with a function to find a bucket ID, and then uses that bucket ID to either store or retrieve the data associated with that key.
In other words, for your case, you just have to provide a hashing function on your data that will give you a bucket ID of your array index.
Perhaps the simplest (and most naive) would be exclusive ORing together all the characters of your key then doing a modulus operation to bring it to the desired range. For example, say you have a structure containing:
You could generate a hash as follows:
This would give you a bucket ID of between 0 and 255 inclusive.
Just keep in mind that the bucket may contain more than one item so you can’t just use the bucket ID as an array index. Each bucket will need to be a structure containing possibly multiple items (such as a linked list or even another hashtable).