package main import "fmt" func main() { m := NewHashMap(5) m.Put("apple", 10) m.Put("banana", 20) fmt.Println(m.Get("apple")) fmt.Println(m.Get("banana")) fmt.Println(m.Get("cherry")) } type entry struct { key string value int next *entry } type HashMap struct { buckets []*entry size int } func NewHashMap(size int) *HashMap { return &HashMap{ buckets: make([]*entry, size), size: size, } } func (h *HashMap) hash(key string) int { hash := 0 for _, c := range key { hash += int(c) } return hash % h.size } func (h *HashMap) Put(key string, value int) { index := h.hash(key) head := h.buckets[index] for e := head; e != nil; e = e.next { if e.key == key { e.value = value return } } newEntry := &entry{key: key, value: value, next: head} h.buckets[index] = newEntry } func (h *HashMap) Get(key string) int { index := h.hash(key) for e := h.buckets[index]; e != nil; e = e.next { if e.key == key { return e.value } } return -1 }
The code puts two key-value pairs: "apple"->10 and "banana"->20. Then it gets the values for "apple", "banana", and "cherry". Since "cherry" was never added, Get returns -1 for it.
The implementation uses chaining with linked lists to handle collisions. New entries are added at the head of the linked list for the bucket.
func (h *HashMap) Remove(key string) {
index := h.hash(key)
var prev *entry
for e := h.buckets[index]; e != nil; e = e.next {
if e.key == key {
if prev == nil {
h.buckets[index] = e.next
} else {
prev.next = e.next
}
return
}
prev = e
}
}If the key is not found, the loop finishes and the function returns without modifying anything. No error occurs.
package main import "fmt" func main() { m := NewHashMap(3) m.Put("cat", 5) m.Put("dog", 7) m.Put("cat", 10) fmt.Println(m.Get("cat")) fmt.Println(m.Get("dog")) } // HashMap and entry types and methods same as previous examples
The second Put call with key "cat" updates its value from 5 to 10. The value for "dog" remains 7.
func (h *HashMap) hash(key string) int { sum := 0 for _, c := range key { sum += int(c) } return sum % h.size } // HashMap size = 4 // Keys inserted: "a", "e", "i", "m", "q", "u"
ASCII values: "a"=97%4=1, "e"=101%4=1, "i"=105%4=1, "m"=109%4=1, "q"=113%4=1, "u"=117%4=1. All keys hash to bucket 1, so 6 entries in bucket 1.
