Simple Hashtable

BlitzMax Forums/BlitzMax Programming/Simple Hashtable

scooter43(Posted 2005) [#1]
Here is a simple Hashtable for the community. Tell me what you think.

Scott Knowles
Flickerpath




ImaginaryHuman(Posted 2005) [#2]
Cool, thanks!

So a hashtable is what's used for, say, a web-browsers cache of images/pages? ... where you see all those folders with long strings of characters?


Bot Builder(Posted 2005) [#3]
Nice job,

A hash table is basically an optimized way of retrieving an object given a name through grouping. You can see this strategy in dictionarys, where words are grouped by their first letter, so the first step in finding a word is to skip to the section of the dictionary with the first letter of the word. This greatly optimizes the process of finding the word. This hash-table calculates a unique number for each word (ok, so words linger than about 8 charachters will make it loop around). This is modded by the capacity of the table, so that an index within the table is computed. Then, it adds the element to the linked list at that location. Upon retrieval, it can simply re-perform the calculation upon the name, and narrow the search down by a great amount. For instance, if you have 200 possible hash instances, on average the amount you have ot search from say, a list, is divided by 200.

There is, however, one error in the code (calcHashCode) that prevents it from working correctly, infact, all elements will have an index of 0, since it uses the variable s rather than the parameter n. Also, this should be a function I think. I also changed the names of some of the methods to be OOP.Example:
Local MH:HashTable=HashTable.Create()

MH.Add("Greeting","Hi")
MH.Add("Cow","Moo")
MH.Add("5+5=","10")
MH.Add("2+2=","4")

Print String(MH.GetObject("Cow"))
Print String(MH.GetObject("Greeting"))
Print String(MH.GetObject("2+2="))



scooter43(Posted 2005) [#4]
Thanks for catching my error... that is what you get for too much copying and pasting from BlitzPlus...

I would prefer to just have a function called Create, Copy, Init and InitCopy, but BlitzMax does not allow for function overloading (same function name, different number of arguments)

Take a look at the code below if my explanation didn't make sense.

If I wanted to inherit from Hashtable, but make another function called Create that takes 2 shorts instead of one.



If I tried to compile this, it would fail because Hashtable's Create only takes a single short, while OptHashtable's Create takes 2 shorts... the compiler complains... check out my post
http://www.blitzbasic.com/Community/posts.php?topic=42732

So I came up with this naming convention

C+<Type Name> = Create Type
CP+<Type Name> = Copy Type
I+<Type Name> = Init Type
IP+<Type Name> = Init Copy Type

I would prefer not having to do this... but you work with what you've got.

Thanks again for the bug fix.