This is a creation in Article, where the information may have evolved or changed.
The original address: http://www.jb51.net/article/56828.htm, this article extracts the set of the part, and the small harmless error has been modified
Java has set set, and Golang No, today suddenly there is a need to a bunch of int slices to combine to heavy, depressed for a long time, their soil method is too high complexity, see the above post feel good happy:
- The map in Golang is not allowed to be duplicated, see this code
M: = map[string]string{"1": "One", "2": "One", "3": "Three",}fmt. PRINTLN (m)//output Map[1:one 2:two 3:three]If I had written this way,M: = map[string]string{"1": "One", "2": "One", "1": "One", "3": "Three",}fmt. Println (M)Program Direct error:duplicate key "1" in map literal
- Through the small example above, the Golang map is not allowed to repeat the key, detailed description see http://golanghome.com/post/155 and Http://www.tuicool.com/articles/RrINZv
- None of the above is important.
- So according to the characteristics of the map, you can create a set of Java sets, thanks again to the original http://www.jb51.net/article/56828.htm Where I added a sort of return result, though it just called a system function, but it felt good. The run test has passed the
Package Mainimport ("FMT" "Sort" "sync") type Set struct {m map[int]boolsync. Rwmutex}func New () *set {return &set{m:map[int]bool{},}}func (S *set) ADD (item int) {S.lock () defer s.unlock () s.m[ite M] = True}func (s *set) Remove (item int) {S.lock () defer s.unlock () Delete (S.M, item)}func (S *set) has (item int) BOOL {S.RL Ock () Defer S.runlock () _, OK: = S.m[item]return Ok}func (s *set) len () int {return Len (S.list ())}func (S *set) Clear () {S.L Ock () defer s.unlock () S.M = Map[int]bool{}}func (S *set) IsEmpty () bool {if s.len () = = 0 {return True}return false}func (s *set) List () []int {s.rlock () defer s.runlock () List: = []int{}for Item: = Range S.M {list = append (list, item)}return list} Func (S *set) sortlist () []int {s.rlock () defer s.runlock () List: = []int{}for Item: = Range S.M {list = append (list, item)} Sort. Ints (list) return List}func main () {//Initialize S: = New () s.add (1) s.add (1) s.add (0) S.add (2) S.add (4) S.add (3) s.clear () if S. IsEmpty () {fmt. Println ("0 item")}s.add (1) s.add (2) S.add (3) if S.has (2) {FMT. PrinTLN ("2 does Exist")}s.remove (2) s.remove (3) fmt. Println ("unordered slices", s.list ()) fmt. PRINTLN ("Ordered slices", s.sortlist ())}