Golang实现简单的ArrayList

list包的ArrayList类

package list

type ArrayList struct {
    elements []interface{}
    size     int
}

func New(values ...interface{}) *ArrayList {
    list := &ArrayList{}
    list.elements = make([]interface{}, 10)
    if len(values) > 0 {
        list.Add(values...)
    }
    return list
}

func (list *ArrayList) Add(values ...interface{}) {
    if list.size+len(values) >= len(list.elements)-1 {
        newElements := make([]interface{}, list.size+len(values)+1)
        copy(newElements, list.elements)
        list.elements = newElements
    }

    for _, value := range values {
        list.elements[list.size] = value
        list.size++
    }

}

func (list *ArrayList) Remove(index int) interface{} {
    if index < 0 || index >= list.size {
        return nil
    }

    curEle := list.elements[index]
    list.elements[index] = nil
    copy(list.elements[index:], list.elements[index+1:list.size])
    list.size--
    return curEle
}

func (list *ArrayList) Get(index int) interface{} {
    if index < 0 || index >= list.size {
        return nil
    }
    return list.elements[index]
}

func (list *ArrayList) IsEmpty() bool {
    return list.size == 0
}

func (list *ArrayList) Size() int {
    return list.size
}
func (list *ArrayList) Contains(value interface{}) bool {
    for _, curValue := range list.elements {
        if curValue == value {
            return true
        }
    }

    return false
}

main包的测试类

package main

import (
    "arrlist/list"
    "fmt"
)

func main() {
    list := list.New()
    list.Add(1, 2, 3, 4, 5)
    i := 0
    for i < list.Size() {
        fmt.Println(list.Get(i))
        i++
    }
    fmt.Println("Size of list:", list.Size())
    fmt.Println(list.Contains(4))
}

程序输出如下,

image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容