Golang实现简单的ArrayList

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

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

查看所有标签

猜你喜欢:

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

100个可操作的网络赚钱方法

100个可操作的网络赚钱方法

陶秋丰 / 云南科技 / 2009-12 / 29.80元

《100个可操作的网络赚钱方法》专为有志于网上创业的读者量身打造,作者是“实战型”的网赚高手,在17岁时就通过互联网创业“年人10万”,如今结合自身的亲身实战经验,与大家分享可以实实在在盈利的100个网络赚钱方法和技巧。内容包括:网站创建与推广、竞价广告、联盟赚钱、网站SEO优化、域名投资、广告投放盈利、威客、博客、淘客赚钱等多个方面。 本手册中作者结合自身的网络赚钱经历,通过具体的、可操作......一起来看看 《100个可操作的网络赚钱方法》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具