Principle and realization of "Golang" HashMap

Source: Internet
Author: User
Tags key string


We all know how to use a map in Golang to store data for a key-value pair type, but what about its internal implementation?

In fact, map is a kind of hashmap, on the surface, it only has the key-value pair structure, actually in the process of storing the key-value pair involves the array and the linked list. HashMap is efficient because it combines both sequential storage (array) and chained storage (linked list) storage structures. The array is the backbone of the hashmap, and there is an element with a type linked list under the array.

This is a simple HASHMAP structure diagram:

HASHMAP structure

When we store a key-value pair, HashMap first converts the key to an array subscript by a hash function, and the real key-value is stored in the corresponding list of the array.

The array of HashMap is often limited, so when the key value to be stored is not enough for many arrays, or the value of the two key value pair is the same as the hash operation, will there be different key-value pairs stored under the same set of numbers? Yes, this is called a hash collision. When a hash collision occurs, the key-value pair is stored on the next node in the array's corresponding list.

In spite of this, the operation efficiency of HashMap is also very high. When there is no hash collision, the lookup complexity is O (1), and the complexity of the hash collision is O (N). So, but the less the list of HashMap in the performance, the better the performance; Of course, when the stored key value pair is very long, it can share some pressure from the storage angle list.

Code implementation


First, HashMap stores a key-value pair, so a key-value pair type is required.

/ / Data type of the data in the linked list structure Key value pairs
Type KV struct {
     Key string
     Value string


Key-value pairs are also primarily stored in the list, so a list class is required.

/ / linked list structure
Type LinkNode struct {
     //node data
     Data KV
     //Next node
     NextNode *LinkNode

/ / Create a linked list with only the head node
Func CreateLink() *LinkNode {

    / / Head node data is empty in order to identify this linked list has not stored key-value pairs
     Var linkNode = &LinkNode{KV{"",""}, nil}

     Return linkNode

When a hash collision occurs, the key-value pair is stored on the newly created list node. Here we need a function to add a node, we use the tail interpolation method to add the node.

/ / Tail insert method to add a node, return the total length of the linked list
Func (link *LinkNode) AddNode(data KV) int {

     Var count = 0
     / / Find the current chain table tail node
     Tail := link
     For {

         Count += 1
         If tail.NextNode == nil {

         }else {

             Tail = tail.NextNode

     Var newNode = &LinkNode{data, nil}
     tail.NextNode = newNode

     Return count+1


Next, is the pig's foot HashMap debut.

//HashMap bucket (array) number
Const BucketCount = 16

Type HashMap struct {
     //HashMap wooden barrel
     Buckets [BucketCount]*LinkNode

/ / Create a HashMap
Func CreateHashMap() *HashMap {

     myMap := &HashMap{}

     / / Add a linked list object for each element
     For i := 0; i < BucketCount ; i++ {

         myMap.Buckets[i] = CreateLink()

     Return myMap

We need a hashing algorithm that converts the key to a 0-bucketcount integer as the subscript for the array that holds it. Here, the hash algorithm should be as random as possible to make the new key-value pairs evenly distributed under each array.

Generally like go map and Java HashMap will have a complex hashing algorithm to achieve this purpose, we are just to talk about the HashMap principle, for the moment, a simple method to find the subscript.

/ / Customize a simple hash algorithm, which can hash keys of different lengths into integers of 0-BucketCount
Func HashCode(key string) int {

     Var sum = 0
     For i := 0; i < len(key); i++ {

         Sum += int(key[i])

     Return (sum % BucketCount)

Adding key-value pairs to the HashMap

/ / Add key value pairs
Func (myMap *HashMap)AddKeyValue(key string, value string) {

     //1. Hash the key into an integer of 0-BucketCount as an array subscript of Map
     Var mapIndex = HashCode(key)

     //2. Get the corresponding array header node
     Var link = myMap.Buckets[mapIndex]

     //3. Add a node to this list
     If link.Data.Key == "" && link.NextNode == nil {
         / / If the current linked list has only one node, indicating that there is no value inserted before modifying the value of the first node, that is, no hash collision occurs.
         link.Data.Key = key
         link.Data.Value = value

         fmt.Printf("node key:%v add to buckets %d first node\n", key, mapIndex)
     }else {

         //Hash collision
         Index := link.AddNode(KV{key, value})
         fmt.Printf("node key:%v add to buckets %d %dth node\n", key, mapIndex, index)

Remove the corresponding value from the HashMap according to the key

/ / button value
Func (myMap *HashMap)GetValueForKey(key string) string {

     //1. Hash the key into an integer of 0-BucketCount as an array subscript of Map
     Var mapIndex = HashCode(key)

     //2. Get the corresponding array header node
     Var link = myMap.Buckets[mapIndex]

     Var value string

     / / Traverse to find the node corresponding to the key
     Head := link
     For {
         If head.Data.Key == key {

             Value = head.Data.Value
         }else {

             Head = head.NextNode

     Return value


package main

import (

func main()  {

    myMap := HashMap.CreateHashMap()
    myMap.AddKeyValue("001", "1")
    myMap.AddKeyValue("002", "2")
    myMap.AddKeyValue("003", "3")
    myMap.AddKeyValue("004", "4")
    myMap.AddKeyValue("005", "5")
    myMap.AddKeyValue("006", "6")
    myMap.AddKeyValue("007", "7")
    myMap.AddKeyValue("008", "8")
    myMap.AddKeyValue("009", "9")
    myMap.AddKeyValue("010", "10")
    myMap.AddKeyValue("011", "11")
    myMap.AddKeyValue("012", "12")
    myMap.AddKeyValue("013", "13")
    myMap.AddKeyValue("012", "14")
    myMap.AddKeyValue("015", "15")



A simple HashMap is implemented, although our hashing algorithm only uses a simple conversion algorithm, which is enough for us to understand the hashmap principle.

For more technical articles, please visit chaors


The internet is disrupting the world and the blockchain is disrupting the internet!

--------------------------------------------------20180710 22:43
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.