Golang实现简单的ArrayList

栏目: Go · 发布时间: 5年前

内容简介:list包的ArrayList类main包的测试类程序输出如下,

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))
}

程序输出如下,

Golang实现简单的ArrayList

image.png


以上所述就是小编给大家介绍的《Golang实现简单的ArrayList》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

JavaScript Patterns

JavaScript Patterns

Stoyan Stefanov / O'Reilly Media, Inc. / 2010-09-21 / USD 29.99

What's the best approach for developing an application with JavaScript? This book helps you answer that question with numerous JavaScript coding patterns and best practices. If you're an experienced d......一起来看看 《JavaScript Patterns》 这本书的介绍吧!

SHA 加密
SHA 加密

SHA 加密工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具