ArrayList 的 Go 语言实现
接口
type List interface {
Size() int
Get(index int) (interface{
}, error)
Set(index int, newValue interface{
}) error
Insert(index int, val interface{
}) error
Append(val ...interface{
})
Delete(index int) error
String() string
Clear()
}
数据结构
type ArrayList struct {
DataStore []interface{
}
TheSize int
}
新建一个ArrayList
func NewArrayList() *ArrayList {
list := new(ArrayList)
list.DataStore = make([]interface{
}, 0, 10)
list.TheSize = 0
return list
}
方法实现
func (list *ArrayList) Size() int {
return list.TheSize
}
func (list *ArrayList) Get(index int) (interface{
}, error) {
if index < 0 || index >= len(list.DataStore) {
return nil, errors.New("索引越界")
}
return list.DataStore[index], nil
}
func (list *ArrayList) Set(index int, newValue interface{
}) error {
if index < 0 || index >= len(list.DataStore) {
return errors.New("索引越界")