Golang HashMap實(shí)現(xiàn)原理解析


- HashMap是一種基于哈希表實(shí)現(xiàn)的鍵值對(duì)存儲(chǔ)結(jié)構(gòu),它通過(guò)哈希函數(shù)將鍵映射到數(shù)組的索引位置,支持高效的插入、查找和刪除操作。其核心原理如下:
- 哈希函數(shù):將鍵轉(zhuǎn)換為數(shù)組索引。理想情況下,不同鍵應(yīng)映射到不同索引,但沖突難以避免。
- 數(shù)組+鏈表:使用數(shù)組作為桶(Bucket),每個(gè)桶是一個(gè)鏈表,解決哈希沖突(鏈地址法)。
- 動(dòng)態(tài)擴(kuò)容:當(dāng)元素?cái)?shù)量超過(guò)容量與負(fù)載因子的乘積時(shí),擴(kuò)容并重新分配元素,保持操作高效性。
package main
import "fmt"
// Entry 鍵值對(duì)鏈表節(jié)點(diǎn)
type Entry struct {
Key string
Value interface{}
Next *Entry
}
// HashMap 哈希表結(jié)構(gòu)
type HashMap struct {
buckets []*Entry // 桶數(shù)組
capacity int // 初始容量
size int // 元素?cái)?shù)量
loadFactor float64 // 負(fù)載因子
}
// NewHashMap 初始化哈希表
func NewHashMap(capacity int) *HashMap {
return &HashMap{
buckets: make([]*Entry, capacity),
capacity: capacity,
loadFactor: 0.75,
}
}
// hash 哈希函數(shù)(FNV-1a算法)
func (h *HashMap) hash(key string) int {
const (
offset = 2166136261
prime = 16777619
)
hash := offset
for _, c := range key {
hash ^= int(c)
hash *= prime
}
return hash
}
// getIndex 計(jì)算鍵對(duì)應(yīng)的桶索引
func (h *HashMap) getIndex(key string) int {
return h.hash(key) % h.capacity
}
// Put 插入鍵值對(duì)
func (h *HashMap) Put(key string, value interface{}) {
if float64(h.size)/float64(h.capacity) >= h.loadFactor {
h.resize()
}
index := h.getIndex(key)
entry := h.buckets[index]
// 遍歷鏈表查找鍵是否存在
for entry != nil {
if entry.Key == key {
entry.Value = value // 存在則更新
return
}
entry = entry.Next
}
// 不存在則插入鏈表頭部
h.buckets[index] = &Entry{
Key: key,
Value: value,
Next: h.buckets[index],
}
h.size++
}
// Get 獲取值
func (h *HashMap) Get(key string) (interface{}, bool) {
index := h.getIndex(key)
entry := h.buckets[index]
for entry != nil {
if entry.Key == key {
return entry.Value, true
}
entry = entry.Next
}
return nil, false
}
// Delete 刪除鍵
func (h *HashMap) Delete(key string) bool {
index := h.getIndex(key)
entry := h.buckets[index]
var prev *Entry
for entry != nil {
if entry.Key == key {
if prev == nil {
h.buckets[index] = entry.Next // 刪除頭節(jié)點(diǎn)
} else {
prev.Next = entry.Next // 中間或尾部節(jié)點(diǎn)
}
h.size--
return true
}
prev = entry
entry = entry.Next
}
return false
}
// resize 擴(kuò)容哈希表
func (h *HashMap) resize() {
newCapacity := h.capacity * 2
newBuckets := make([]*Entry, newCapacity)
for i := 0; i < h.capacity; i++ {
entry := h.buckets[i]
for entry != nil {
next := entry.Next
newIndex := h.hash(entry.Key) % newCapacity // 重新計(jì)算索引
entry.Next = newBuckets[newIndex] // 插入新桶頭部
newBuckets[newIndex] = entry
entry = next
}
}
h.buckets = newBuckets
h.capacity = newCapacity
}
func main() {
hm := NewHashMap(2) // 初始容量設(shè)為2便于觸發(fā)擴(kuò)容
hm.Put("name", "Alice")
hm.Put("age", 30)
hm.Put("lang", "Go") // 觸發(fā)擴(kuò)容
if val, ok := hm.Get("name"); ok {
fmt.Println("name:", val) // 輸出 Alice
}
hm.Delete("age")
if _, ok := hm.Get("age"); !ok {
fmt.Println("age deleted") // 輸出此句
}
}到此這篇關(guān)于Golang HashMap實(shí)現(xiàn)原理的文章就介紹到這了,更多相關(guān)goland hashmap原理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- golang中有序Map的實(shí)現(xiàn)
- Go 中的Map與字符處理指南
- Go數(shù)據(jù)結(jié)構(gòu)之映射map方式
- Go語(yǔ)言sync.Map實(shí)現(xiàn)高并發(fā)場(chǎng)景下的安全映射
- golang讀寫(xiě)分離sync.Map的使用
- golang遍歷map的方法小結(jié)
- Go中map數(shù)據(jù)類(lèi)型的實(shí)現(xiàn)
- Go語(yǔ)言中的map擴(kuò)容機(jī)制
- Go語(yǔ)言如何實(shí)現(xiàn)線(xiàn)程安全的Map
- 關(guān)于Golang的Map的線(xiàn)程安全問(wèn)題的解決方案
- go開(kāi)發(fā)過(guò)程中mapstructure使用示例詳解
- Go?語(yǔ)言中映射(Map)使用場(chǎng)景小結(jié)
相關(guān)文章
Golang 端口復(fù)用測(cè)試的實(shí)現(xiàn)
這篇文章主要介紹了Golang 端口復(fù)用測(cè)試的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
Go 1.21新增的slices包中切片函數(shù)用法詳解
Go 1.21新增的 slices 包提供了很多和切片相關(guān)的函數(shù),可以用于任何類(lèi)型的切片,本文通過(guò)代碼示例為大家介紹了部分切片函數(shù)的具體用法,感興趣的小伙伴可以了解一下2023-08-08
Go 語(yǔ)言結(jié)構(gòu)實(shí)例分析
在本篇文章里小編給大家整理的是一篇關(guān)于Go 語(yǔ)言結(jié)構(gòu)實(shí)例分析的相關(guān)知識(shí)點(diǎn),有興趣的朋友們可以學(xué)習(xí)下。2021-07-07
Go語(yǔ)言for range(按照鍵值循環(huán))遍歷操作
這篇文章主要介紹了Go語(yǔ)言for range(按照鍵值循環(huán))遍歷操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-12-12
golang 實(shí)現(xiàn)時(shí)間戳和時(shí)間的轉(zhuǎn)化
這篇文章主要介紹了golang 實(shí)現(xiàn)時(shí)間戳和時(shí)間的轉(zhuǎn)化操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-05-05
Go語(yǔ)言使用sort包對(duì)任意類(lèi)型元素的集合進(jìn)行排序的方法
這篇文章主要介紹了Go語(yǔ)言使用sort包對(duì)任意類(lèi)型元素的集合進(jìn)行排序的方法,實(shí)例分析了sort排序所涉及的方法與相關(guān)的使用技巧,需要的朋友可以參考下2015-02-02

