Golang实现简单的ArrayList

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

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

查看所有标签

猜你喜欢:

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

创业之初你不可不知的融资知识

创业之初你不可不知的融资知识

桂曙光 / 机械工业出版社 / 2010-6-1 / 48.00元

从零到精通 成功融资必读书 像小说一样好看的趣味融资书 手把手教你找到VC拿到钱 本书以创业者寻找风险投资的逻辑顺序为主线,运用理论分析和实例剖析相结合的手法,将简洁、通俗的语言与丰富的图表工具相结合,辅以中肯的建议,同时运用大量鲜活的、有代表性的成败案例,为读者解读创业之初企业有效成功融资的途径和方法,帮助你的企业开创新的辉煌。一起来看看 《创业之初你不可不知的融资知识》 这本书的介绍吧!

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

在线压缩/解压 JS 代码

SHA 加密
SHA 加密

SHA 加密工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具