Simple hash map implementation with collision handling using chaining
package main
import (
"fmt"
"hash/fnv"
)
type HashNode struct {
key string
value interface{}
next *HashNode
}
type HashMap struct {
buckets []*HashNode
size int
}
func NewHashMap(size int) *HashMap {
return &HashMap{
buckets: make([]*HashNode, size),
size: size,
}
}
func (hm *HashMap) hash(key string) int {
h := fnv.New32a()
h.Write([]byte(key))
return int(h.Sum32()) % hm.size
}
func (hm *HashMap) Put(key string, value interface{}) {
index := hm.hash(key)
if hm.buckets[index] == nil {
hm.buckets[index] = &HashNode{key: key, value: value}
return
}
current := hm.buckets[index]
for current != nil {
if current.key == key {
current.value = value
return
}
if current.next == nil {
break
}
current = current.next
}
current.next = &HashNode{key: key, value: value}
}
func (hm *HashMap) Get(key string) (interface{}, bool) {
index := hm.hash(key)
current := hm.buckets[index]
for current != nil {
if current.key == key {
return current.value, true
}
current = current.next
}
return nil, false
}
func main() {
hashMap := NewHashMap(10)
hashMap.Put("name", "John")
hashMap.Put("age", 30)
hashMap.Put("city", "New York")
if value, exists := hashMap.Get("name"); exists {
fmt.Printf("Name: %v\n", value)
}
}
Views
Lines
Characters
Likes