package Map
import (
"fmt"
"testing"
)
/*
实现一个Map
*/
type entity struct {
Key interface{}
Value interface{}
}
type MAP struct {
entities []entity
len int
}
func NewMAP(cap int) *MAP {
if cap < 0 {
cap = 10
}
return &MAP{entities: make([]entity,0 , cap)}
}
func (m *MAP)Add(key,value interface{}) {
for i := 0; i < len(m.entities); i++ {
if m.entities[i].Key == key {
m.entities[i].Value = value
return
}
}
m.len++
m.entities = append(m.entities,entity{
Key: key,
Value: value,
})
}
func (m *MAP)Remove(key interface{}) {
for i := 0; i < len(m.entities); i++ {
if m.entities[i].Key == key {
e1 := m.entities[:i]
e1 = append(e1,m.entities[i+1:]...)
m.len--
m.entities = e1
return
}
}
}
func (m *MAP)Len() int {
return m.len
}
func TestMAP(t *testing.T) {
mp := NewMAP(10)
mp.Add(1000,1000)
mp.Add(100,100)
mp.Add(50,50)
fmt.Println(mp.Len())
mp.Remove(50)
fmt.Println(mp.Len())
mp.Add("hello","hello")
mp.Add("hello","world")
fmt.Println(mp.Len())
mp.Remove("hello")
}
用切片实现一个简陋的Map
最新推荐文章于 2024-01-28 22:37:20 发布