HashMap principle and implementation

Source: Internet
Author: User

Principle

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

Kvmap

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

Data type key value of data in linked list structure typekvstruct{keystringvaluestring}

Linknode

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

Linked list structure typelinknodestruct{//node data kv//next node NextNode *linknode}//create a linked list with only the head node Funccreatelink () *linknode{//header node data is empty is to identify that the list has not yet stored the key value pair Varlinknode = &linknode{kv{"", "" "},nil}returnlinknode}

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.

The end interpolation method adds a node that returns the total length of the list of Func (link *linknode) AddNode (datakv) int {varcount=0//Find the current linked footer node Tail: = Linkfor{count+=1iftail. nextnode==nil{break}else{tail = tail. NextNode}}varnewnode = &linknode{data,nil} tail. Nextnode= Newnodereturncount+1}

HashMap

Next, is the pig's foot HashMap debut.

Number of HashMap barrels (arrays) constbucketcount =16typehashmapstruct{//hashmap barrels Buckets [bucketcount]*linknode}//        Create Hashmapfunccreatehashmap () *hashmap{MyMap: = &hashmap{}//Add a list object for each element fori: =0; i < Bucketcount; i++ { Mymap.buckets[i] = Createlink ()}returnmymap}

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 hashing algorithm that hashes different lengths of keys to 0-bucketcount integers Funchashcode (keystring) int{varsum =0fori: =0; i

Add key values to the HashMap here, by the way, we recommend an architecture Exchange Group: 617434785, which will share some of the senior architect recorded video recordings: Spring,mybatis,netty source analysis, high concurrency, high performance, distributed, micro-service architecture principles, JVM performance Optimization These become the necessary knowledge systems for architects. You can also receive free learning resources. I believe that for those who have worked and have encountered technical bottlenecks, there will be content in this group that you need.

Add a key value pair func (MyMap *hashmap) addkeyvalue (keystring, valuestring) {//1. An integer that hashes the key to 0-bucketcount as the array subscript for the map Varmapindex = Hashcode (key)//2. Gets the corresponding array header node Varlink = MYMAP.BUCKETS[MAPINDEX]//3. Add node Iflink in this list. Data.key = = "" && link. NextNode ==nil{//If the current list has only one node, the description does not have a value inserted before modifying the value of the first node without a hash collision link. Data.key = Key link. Data.value = Value FMT. Printf ("node key:%v add to buckets%d first node\n", Key, Mapindex)}else{//occurs a 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

Key value func (MyMap *hashmap) Getvalueforkey (keystring) string{//1. An integer that hashes the key to 0-bucketcount as the array subscript for the map Varmapindex = Hashcode (Key)//2. Get the corresponding array header node Varlink = mymap.buckets[mapindex]varvaluestring//traverse to find the nodes corresponding to key head: = Linkfor{ifhead. Data.key = = Key {value = head. data.valuebreak}else{head = head. NextNode}}returnvalue}

Main_test

Packagemainimport ("Chaors.com/learngo/blockchaincryptography/hashmap") Funcmain () {myMap: = Hashmap.createhashmap ( ) Mymap.addkeyvalue ("001", "1") Mymap.addkeyvalue ("002", "2") Mymap.addkeyvalue ("003", "3") Mymap.addkeyvalue ("00 4 "," 4 ") Mymap.addkeyvalue (" 005 "," 5 ") Mymap.addkeyvalue (" 006 "," 6 ") Mymap.addkeyvalue (" 007 "," 7 ") Mymap.addkeyval UE ("008", "8") Mymap.addkeyvalue ("009", "9") Mymap.addkeyvalue ("010", "Ten") Mymap.addkeyvalue ("011", "one") mymap.a Ddkeyvalue ("012", "a") Mymap.addkeyvalue ("013", "" ") Mymap.addkeyvalue (" 012 "," + ") Mymap.addkeyvalue (" 015 "," 15 ")}

RUN

Main_test.png

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.

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: info-contact@alibabacloud.com 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.