<p>The point of this question is to collect a list of examples of hashtable implementations using arrays in different languages. It would also be nice if someone could throw in a pretty detailed overview of how they work, and what is happening with each example. </p>

<p><strong>Edit:</strong> </p>

<p>Why not just use the built in hash functions in your specific language? </p>

<p>Because we should know how hash tables work and be able to implement them. This may not seem like a super important topic, but knowing how one of the most used data structures works seems pretty important to me. If this is to become the wikipedia of programming, then these are some of the types of questions that I will come here for. I'm not looking for a CS book to be written here. I could go pull Intro to Algorithms off the shelf and read up on the chapter on hash tables and get that type of info. More specifically what I am looking for are <strong>code examples</strong>. Not only for me in particular, but also for others who would maybe one day be searching for similar info and stumble across this page. </p>

<p>To be more specific: If you <strong>had</strong> to implement them, and could not use built-in functions, how would you do it? </p>

<p>You don't need to put the code here. Put it in pastebin and just link it. </p>

[{'answer_id': 25298, 'author': 'Jason Z', 'author_id': 2470, 'author_profile': 'https://Stackoverflow.com/users/2470', 'pm_score': 0, 'selected': False, 'text': '<p>I think you need to be a little more specific.  There are several variations on hashtables with regards to the following options</p>\n\n<ul>\n<li>Is the hashtable fixed-size or dynamic?</li>\n<li>What type of hash function is used?</li>\n<li>Are there any performance constraints when the hashtable is resized?</li>\n</ul>\n\n<p>The list can go on and on.  Each of these constraints could lead to multiple implementations in any language.</p>\n\n<p>Personally, I would just use the built-in hashtable that is available in my language of choice.  The only reason I would even consider implementing my own would be due to performance issues, and even then it is difficult to beat most existing implementations.</p>\n'}, {'answer_id': 25299, 'author': 'Daren Thomas', 'author_id': 2260, 'author_profile': 'https://Stackoverflow.com/users/2260', 'pm_score': -1, 'selected': False, 'text': '<p>I went and read some of the Wikipedia-page on hashing: <a href="http://en.wikipedia.org/wiki/Hash_table" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Hash_table</a>. It seems like a lot of work, to put up code for a hashtable here, especially since most languages I use allready have them built in. Why would you want implementations here? This stuff really belongs in a languages library.</p>\n\n<p>Please elaborate on what your expected solutions should include:</p>\n\n<ul>\n<li>hash function</li>\n<li>variable bucket count</li>\n<li>collision behavior</li>\n</ul>\n\n<p>Also state what the purpose of collecting them here is. Any serious implementation will easily be quite a mouthfull = this will lead to very long answers (possibly a few pages long each). You might also be enticing people to copy code from a library...</p>\n'}, {'answer_id': 25341, 'author': 'mmattax', 'author_id': 1638, 'author_profile': 'https://Stackoverflow.com/users/1638', 'pm_score': 3, 'selected': False, 'text': '<p>A HashTable is a really simple concept: it is an array in which key and value pairs are placed into, (like an associative array) by the following scheme:</p>\n\n<p>A hash function hashes the key to a (hopefully) unused index into the array. the value is then placed into the array at that particular index.</p>\n\n<p>Data retrieval is easy, as the index into the array can be calculated via the hash function, thus look up is ~ O(1).</p>\n\n<p>A problem arises when a hash function maps 2 different keys to the same index...there are many ways of handling this which I will not detail here...</p>\n\n<p>Hash tables are a fundamental way of storing and retrieving data quickly, and are "built in"  in nearly all programming language libraries. </p>\n'}, {'answer_id': 25365, 'author': 'SemiColon', 'author_id': 1994, 'author_profile': 'https://Stackoverflow.com/users/1994', 'pm_score': 4, 'selected': False, 'text': '<p>A hash table a data structure that allows lookup of items in constant time.  It works by hashing a value and converting that value to an offset in an array.  The concept of a hash table is fairly easy to understand, but implementing is obviously harder.  I\'m not pasting the whole hash table here, but here are some snippets of a hash table I made in C a few weeks ago...</p>\n\n<p>One of the basics of creating a hash table is having a good hash function.  I used the djb2 hash function in my hash table:</p>\n\n<pre><code>int ComputeHash(char* key)\n{\n    int hash = 5381;\n    while (*key)\n    hash = ((hash &lt;&lt; 5) + hash) + *(key++);\n    return hash % hashTable.totalBuckets;\n}\n</code></pre>\n\n<p>Then comes the actual code itself for creating and managing the buckets in the table</p>\n\n<pre><code>typedef struct HashTable{\n    HashTable* nextEntry;\n    char*      key;\n    char*      value;\n}HashBucket;\n\ntypedef struct HashTableEntry{\n    int totalBuckets;       // Total number of buckets allocated for the hash table\n    HashTable** hashBucketArray; // Pointer to array of buckets\n}HashTableEntry;\nHashTableEntry hashTable;\n\nbool InitHashTable(int totalBuckets)\n{\n    if(totalBuckets &gt; 0)\n    {\n        hashTable.totalBuckets = totalBuckets;\n        hashTable.hashBucketArray = (HashTable**)malloc(totalBuckets * sizeof(HashTable));\n        if(hashTable.hashBucketArray != NULL)\n        {\n            memset(hashTable.hashBucketArray, 0, sizeof(HashTable) * totalBuckets);\n            return true;\n        }\n    }\n    return false;\n}\n\nbool AddNode(char* key, char* value)\n{\n    int offset = ComputeHash(key);\n    if(hashTable.hashBucketArray[offset] == NULL)\n    {\n        hashTable.hashBucketArray[offset] = NewNode(key, value);\n        if(hashTable.hashBucketArray[offset] != NULL)\n            return true;\n    }\n\n    else\n    {\n        if(AppendLinkedNode(hashTable.hashBucketArray[offset], key, value) != NULL)\n            return true;\n    }\n    return false;\n}\n\nHashTable* NewNode(char* key, char* value)\n{\n    HashTable* tmpNode = (HashTable*)malloc(sizeof(HashTable));\n    if(tmpNode != NULL)\n    {\n        tmpNode-&gt;nextEntry = NULL;\n        tmpNode-&gt;key   = (char*)malloc(strlen(key));\n        tmpNode-&gt;value = (char*)malloc(strlen(value));\n\n        strcpy(tmpNode-&gt;key, key);\n        strcpy(tmpNode-&gt;value, value);\n    }\n    return tmpNode;\n}\n</code></pre>\n\n<p>AppendLinkedNode finds the last node in the linked list and appends a new node to it.</p>\n\n<p>The code would be used like this:</p>\n\n<pre><code>if(InitHashTable(100) == false) return -1;\nAddNode("10", "TEN");\n</code></pre>\n\n<p>Finding a node is a simple as:</p>\n\n<pre><code>HashTable* FindNode(char* key)\n{\n    int offset = ComputeHash(key);\n    HashTable* tmpNode = hashTable.hashBucketArray[offset];\n    while(tmpNode != NULL)\n    {\n        if(strcmp(tmpNode-&gt;key, key) == 0)\n            return tmpNode;\n        tmpNode = tmpNode-&gt;nextEntry;\n    }\n    return NULL;\n}\n</code></pre>\n\n<p>And is used as follows:</p>\n\n<pre><code>char* value = FindNode("10");\n</code></pre>\n'}, {'answer_id': 626569, 'author': 'Nick Van Brunt', 'author_id': 30470, 'author_profile': 'https://Stackoverflow.com/users/30470', 'pm_score': 2, 'selected': False, 'text': '<p>I was looking for a completely portable C hash table implementation and became interested in how to implement one myself.  After searching around a bit I found:\n<a href="http://www.eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx" rel="nofollow noreferrer"> Julienne Walker\'s The Art of Hashing</a> which has some great tutorials on hashing and hash tables.  Implementing them is a bit more complex than I thought but it was a great read.</p>\n'}, {'answer_id': 828242, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>For those who may use the code above, note the memory leak:</p>\n\n<pre><code>tmpNode-&gt;key   = (char*)malloc(strlen(key)+1);   //must have +1 for '\\0'\ntmpNode-&gt;value = (char*)malloc(strlen(value)+1); //must have +1\nstrcpy(tmpNode-&gt;key, key);\nstrcpy(tmpNode-&gt;value, value);\n</code></pre>\n\n<p>And to complete the code:</p>\n\n<pre><code>HashNode* AppendLinkedNode(HashNode* ptr, char* key, char* value)\n{\n    //follow pointer till end\n    while (ptr-&gt;nextEntry!=NULL)\n    {\n        if (strcmp(ptr-&gt;value,value)==0) return NULL;\n        ptr=ptr-&gt;nextEntry;\n    }\n    ptr-&gt;nextEntry=newNode(key,value);\n    return ptr-&gt;nextEntry;\n}\n</code></pre>\n"}, {'answer_id': 1148515, 'author': 'Pranav', 'author_id': 58385, 'author_profile': 'https://Stackoverflow.com/users/58385', 'pm_score': 1, 'selected': False, 'text': '<p>Here is my code for a Hash Table, implemented in Java. Suffers from a minor glitch- the key and value fields are not the same. Might edit that in the future. </p>\n\n<pre><code>public class HashTable\n{\n    private LinkedList[] hashArr=new LinkedList[128];\n    public static int HFunc(int key)\n    {\n        return key%128;\n    }\n\n\n    public boolean Put(Val V)\n    {\n\n        int hashval = HFunc(V.getKey());\n        LinkedNode ln = new LinkedNode(V,null);\n        hashArr[hashval].Insert(ln);\n        System.out.println("Inserted!");\n        return true;            \n    }\n\n    public boolean Find(Val V)\n    {\n        int hashval = HFunc(V.getKey());\n        if (hashArr[hashval].getInitial()!=null &amp;&amp; hashArr[hashval].search(V)==true)\n        {\n            System.out.println("Found!!");\n            return true;\n        }\n        else\n        {\n            System.out.println("Not Found!!");\n            return false;\n        }\n\n    }\n    public boolean delete(Val v)\n    {\n        int hashval = HFunc(v.getKey());\n        if (hashArr[hashval].getInitial()!=null &amp;&amp; hashArr[hashval].delete(v)==true)\n        {\n            System.out.println("Deleted!!");\n            return true;\n        }\n        else \n        {\n            System.out.println("Could not be found. How can it be deleted?");\n            return false;\n        }\n    }\n\n    public HashTable()\n    {\n        for(int i=0; i&lt;hashArr.length;i++)\n            hashArr[i]=new LinkedList();\n    }\n\n}\n\nclass Val\n{\n    private int key;\n    private int val;\n    public int getKey()\n    {\n        return key;\n    }\n    public void setKey(int k)\n    {\n        this.key=k;\n    }\n    public int getVal()\n    {\n        return val;\n    }\n    public void setVal(int v)\n    {\n        this.val=v;\n    }\n    public Val(int key,int value)\n    {\n        this.key=key;\n        this.val=value;\n    }\n    public boolean equals(Val v1)\n    {\n        if (v1.getVal()==this.val)\n        {\n            //System.out.println("hello im here");\n            return true;\n        }\n        else \n            return false;\n    }\n}\n\nclass LinkedNode\n{\n    private LinkedNode next;\n    private Val obj;\n    public LinkedNode(Val v,LinkedNode next)\n    {\n        this.obj=v;\n        this.next=next;\n    }\n    public LinkedNode()\n    {\n        this.obj=null;\n        this.next=null;\n    }\n    public Val getObj()\n    {\n        return this.obj;    \n    }\n    public void setNext(LinkedNode ln)\n    {\n        this.next = ln;\n    }\n\n    public LinkedNode getNext()\n    {\n        return this.next;\n    }\n    public boolean equals(LinkedNode ln1, LinkedNode ln2)\n    {\n        if (ln1.getObj().equals(ln2.getObj()))\n        {\n            return true;\n        }\n        else \n            return false;\n\n    }\n\n}\n\nclass LinkedList\n{\n    private LinkedNode initial;\n    public LinkedList()\n    {\n        this.initial=null;\n    }\n    public LinkedList(LinkedNode initial)\n    {\n        this.initial = initial;\n    }\n    public LinkedNode getInitial()\n    {\n        return this.initial;\n    }\n    public void Insert(LinkedNode ln)\n    {\n        LinkedNode temp = this.initial;\n        this.initial = ln;\n        ln.setNext(temp);\n    }\n    public boolean search(Val v)\n    {\n        if (this.initial==null)\n            return false;\n        else \n        {\n            LinkedNode temp = this.initial;\n            while (temp!=null)\n            {\n                //System.out.println("encountered one!");\n                if (temp.getObj().equals(v))\n                    return true;\n                else \n                    temp=temp.getNext();\n            }\n            return false;\n        }\n\n    }\n    public boolean delete(Val v)\n    {\n        if (this.initial==null)\n            return false;\n        else \n        {\n            LinkedNode prev = this.initial;\n            if (prev.getObj().equals(v))\n            {\n                this.initial = null;\n                return true;\n            }\n            else\n            {\n                LinkedNode temp = this.initial.getNext();\n            while (temp!=null)\n            {\n                if (temp.getObj().equals(v))\n                {\n                    prev.setNext(temp.getNext());\n                    return true;\n                }\n                else\n                {\n                    prev=temp;\n                    temp=temp.getNext();\n                }\n            }\n            return false;\n            }\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 2901567, 'author': 'J D', 'author_id': 13924, 'author_profile': 'https://Stackoverflow.com/users/13924', 'pm_score': 0, 'selected': False, 'text': "<p>Minimal implementation in F# as a function that builds a hash table from a given sequence of key-value pairs and returns a function that searches the hash table for the value associated with the given key:</p>\n\n<pre><code>&gt; let hashtbl xs =\n    let spine = [|for _ in xs -&gt; ResizeArray()|]\n    let f k = spine.[abs(k.GetHashCode()) % spine.Length]\n    Seq.iter (fun (k, v) -&gt; (f k).Add (k, v)) xs\n    fun k -&gt; Seq.pick (fun (k', v) -&gt; if k=k' then Some v else None) (f k);;\nval hashtbl : seq&lt;'a * 'b&gt; -&gt; ('a -&gt; 'b) when 'a : equality\n</code></pre>\n"}, {'answer_id': 11068369, 'author': 'Korbi', 'author_id': 2555491, 'author_profile': 'https://Stackoverflow.com/users/2555491', 'pm_score': 3, 'selected': False, 'text': '<p>A Java implementation in &lt; 60 LoC</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Random;\n\n\npublic class HashTable {\n\n    class KeyValuePair {\n\n        Object key;\n\n        Object value;\n\n        public KeyValuePair(Object key, Object value) {\n            this.key = key;\n            this.value = value;\n        }\n    }\n\n    private Object[] values;\n\n    private int capacity;\n\n    public HashTable(int capacity) {\n        values = new Object[capacity];\n        this.capacity = capacity;\n    }\n\n    private int hash(Object key) {\n        return Math.abs(key.hashCode()) % capacity;\n    }\n\n    public void add(Object key, Object value) throws IllegalArgumentException {\n\n        if (key == null || value == null)\n            throw new IllegalArgumentException("key or value is null");\n\n        int index = hash(key);\n\n        List&lt;KeyValuePair&gt; list;\n        if (values[index] == null) {\n            list = new ArrayList&lt;KeyValuePair&gt;();\n            values[index] = list;\n\n        } else {\n            // collision\n            list = (List&lt;KeyValuePair&gt;) values[index];\n        }\n\n        list.add(new KeyValuePair(key, value));\n    }\n\n    public Object get(Object key) {\n        List&lt;KeyValuePair&gt; list = (List&lt;KeyValuePair&gt;) values[hash(key)];\n        if (list == null) {\n            return null;\n        }\n        for (KeyValuePair kvp : list) {\n            if (kvp.key.equals(key)) {\n                return kvp.value;\n            }\n        }\n        return null;\n    }\n\n    /**\n     * Test\n     */\n    public static void main(String[] args) {\n\n        HashTable ht = new HashTable(100);\n\n        for (int i = 1; i &lt;= 1000; i++) {\n            ht.add("key" + i, "value" + i);\n        }\n\n        Random random = new Random();\n        for (int i = 1; i &lt;= 10; i++) {\n            String key = "key" + random.nextInt(1000);\n            System.out.println("ht.get(\\"" + key + "\\") = " + ht.get(key));\n        }   \n    }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/25282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1797/']