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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

零基础学Minecraft编程

零基础学Minecraft编程

Martin O''Hanlon、David Whale / 中文Minecraft Wiki翻译团队 / 人民邮电出版社 / 2015-9-7 / 79

在你体验Minecraft冒险的同时,学习宝贵的编程技能! 如果你很喜欢玩Minecraft,却被游戏中的建造耗费大量时间而困扰,并且你想要对游戏添加一些改动,那么本书就是为你而设计的。在游戏中,你可以学习许多Python编程技能,在PC、Mac或树莓派上与游戏进行互动。这些冒险不仅局限在虚拟世界——你也将会学习如何将Minecraft与电子元件连接起来,这样你的Minecraft世界就能够......一起来看看 《零基础学Minecraft编程》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具