注意:還沒有解決hash沖突和hash傾斜的問題。
package main
import "fmt"
var nowCapacity = 10 //當前容量
const maxCapacity = 100 //最大容量
const loadFactor = 0.75 //負載因子(決定擴容因數(shù))
type Entry struct {
k string //key
v interface{} //值
next *Entry
}
type HashMap struct {
size int //map的大小
bucket []Entry //存放數(shù)據(jù)的桶,為slice
}
//創(chuàng)建一個CreateHashMap的函數(shù),返回一個HashMap指針
func CreateHashMap() *HashMap {
hm := &HashMap{0, make([]Entry, nowCapacity, maxCapacity)}
return hm
}
//創(chuàng)建一個Put函數(shù)入?yún)⑹莐ey和value對HashMap進行插入操作
func (hm *HashMap) Put(k string, v interface{}) {
entry := Entry{k, v, nil}
//插入HashMap中
hm.insert(entry)
//如果比例大于負載因子就需要擴容
if float64(hm.size)/float64(len(hm.bucket)) > loadFactor {
if nowCapacity*2 > maxCapacity {
nowCapacity = maxCapacity
} else {
nowCapacity = nowCapacity * 2
}
//創(chuàng)建一個新的HashMap
newHm := HashMap{0, make([]Entry, nowCapacity, maxCapacity)}
//遍歷所有的entry,插入新的HashMap中(原來的數(shù)據(jù)遷移)
for _, v := range hm.bucket {
if v.k == "" {
continue
}
for v.next != nil {
newHm.insert(v)
v = *v.next
}
newHm.insert(v)
}
newHm.size = hm.size
//通過指針賦值新的Map
*hm = newHm
}
}
//真正的插入函數(shù)
func (hm *HashMap) insert(entry Entry) {
//計算entry的插入位置
index := hashCode(entry.k, nowCapacity)
//根據(jù)計算出來的位置,獲得當前位置第一個entry位置的指針
e := &hm.bucket[index]
//判斷第一個位置entry的key是不是空字符串,
//如果是空,直接插入;
if e.k == "" {
hm.size++
*e = entry
return
} else {
//循環(huán)當前位置上所有entry,
//如果有entry的key和當前要插入的entry的key相等就進行覆蓋
for e.next != nil {
if e.k == entry.k {
*e = entry
return
}
//直達最后一個entry
e = e.next
}
//判斷鏈表尾部entry的key和當前要插入的entry的key是否相等
//相等就進行覆蓋,沒有就將新的entry插入到鏈表的末尾
if e.k == entry.k {
*e = entry
return
}
hm.size++
e.next = &entry
}
}
//查詢方法:Get
func (hm *HashMap) Get(k string) interface{} {
//通過hash函數(shù)查詢出k在slice存放的位置
index := hashCode(k, nowCapacity)
//或者計算位置的entry指針(或者說鏈表)
e := &hm.bucket[index]
//查詢結(jié)果為空
if e.k == "" {
return nil
} else {
//遍歷
for e.next != nil {
if e.k == k {
return e.v
}
//直到鏈表最后
e = e.next
}
//通過hash函數(shù)查詢出k在slice存放的位置
if e.k == k {
return e.v
}
return nil
}
}
//自定義散列函數(shù)(得出存放位置)
func hashCode(k string, length int) int {
sum := 0
b := []byte(k)
for _, v := range b {
sum += int(v)
}
return sum % length
}
func main() {
hm := CreateHashMap()
hm.Put("a", 1)
hm.Put("b", 2)
hm.Put("c", "c")
hm.Put("d", "c")
hm.Put("e", "c")
hm.Put("f", "f")
hm.Put("g", "g")
hm.Put("h", "h")
hm.Put("c", "kkkk")
fmt.Println(hm.Get("a"))
fmt.Println(hm.Get("b"))
fmt.Println(hm.Get("c"))
fmt.Println(hm.Get("g"))
fmt.Println(hm.Get("h"))
fmt.Println(hm)
}
參考:
1.go中map實現(xiàn)的原理
- 理解Golang哈希表Map的元素
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。