Go实现集合set

package main
//支持任意类型添加
import (
	"fmt"
	"sync"
)

type inter interface{}

type Set struct {
	m map[inter]bool
	sync.RWMutex
}

func New() *Set {
	return &Set{
		m: map[inter]bool{},
	}
}
func (s *Set) Add(item inter) {
	s.Lock()
	defer s.Unlock()
	s.m[item] = true
}
func (s *Set) Remove(item inter) {
	s.Lock()
	s.Unlock()
	delete(s.m, item)
}
func (s *Set) Has(item inter) bool {
	s.RLock()
	defer s.RUnlock()
	_, ok := s.m[item]
	return ok
}
func (s *Set) Len() int {
	return len(s.List())
}
func (s *Set) Clear() {
	s.Lock()
	defer s.Unlock()
	s.m = map[inter]bool{}
}
func (s *Set) IsEmpty() bool {
	if s.Len() == 0 {
		return true
	}
	return false
}
func (s *Set) List() []inter {
	s.RLock()
	defer s.RUnlock()
	list := []inter{}
	for item := range s.m {
		list = append(list, item)
	}
	return list
}

func main() {
	s := New()
	s.Add(11)
	s.Add("aa")
	for i, k := range s.List() {
		fmt.Println(i, k)
	}
}

  

posted @ 2015-02-09 13:34  huangxiaohen  阅读(1631)  评论(0编辑  收藏  举报