51-ArrayList
Collection 类型介绍
仓颉中常用的几种基础 Collection 类型,包含 Array、ArrayList、HashSet、HashMap。
可以在不同的场景中选择适合对应业务的类型:
- Array:如果不需要增加和删除元素,但需要修改元素,就应该使用它。
- ArrayList:如果需要频繁对元素增删查改,就应该使用它。
- HashSet:如果希望每个元素都是唯一的,就应该使用它。
- HashMap:如果希望存储一系列的映射关系,就应该使用它。
下表是这些类型的基础特性:
类型名称 | 元素可变 | 增删元素 | 元素唯一性 | 有序序列 |
---|---|---|---|---|
Array<T> | Y | N | N | Y |
ArrayList<T> | Y | Y | N | Y |
HashSet<T> | N | Y | Y | N |
HashMap<K, V> | K: N, V: Y | Y | K: Y, V: N | N |
ArrayList 初始化
需要先导入。
import std.collection.*
ArrayList支持多种初始化方式
package pro
import std.collection.*main() {// 创建默认初始容量(10)的空字符串列表let a = ArrayList<String>()// 创建初始容量为100的空字符串列表let b = ArrayList<String>(100)// 从静态数组初始化Int64列表(元素0,1,2)let c = ArrayList<Int64>([0, 1, 2])// 拷贝构造函数:创建与列表c内容相同的副本let d = ArrayList<Int64>(c)// 使用生成函数初始化:创建容量为2的字符串列表// 通过lambda表达式将Int64值转换为字符串let e = ArrayList<String>(2, {x: Int64 => x.toString()})
}
ArrayList 初始化 访问
支持直接使用下标进行访问。
let c = ArrayList<Int64>([0, 1, 2])
println(c[1])
通过size访问列表的长度。
println(c.size)
可以通过forin访问列表内的所有成员。
let list = ArrayList<Int64>([0, 1, 2])
for (i in list) {println("The element is ${i}")
}
ArrayList 初始化 修改
可以通过下标直接修改
let list = ArrayList<Int64>([0, 1, 2])
list[0] = 3
ArrayList 初始化 增加
在列表末尾增加元素使用append 和appendAll ,在指定位置插入元素使用insert和insertAll
let list = ArrayList<Int64>()
list.append(0) // list contains element 0
list.append(1) // list contains elements 0, 1
let li = [2, 3]
list.appendAll(li) // list contains elements 0, 1, 2, 3let list = ArrayList<Int64>([0, 1, 2]) // list contains elements 0, 1, 2
list.insert(1, 4) // list contains elements 0, 4, 1, 2
如果知道大约需要添加多少个元素,可以在添加之前预备足够的内存以避免中间重新分配,这样可以提升性能表现。
let list = ArrayList<Int64>(100) // Allocate space at oncefor (i in 0..100) {list.append(i) // Does not trigger reallocation of space}list.reserve(100) // Prepare more spacefor (i in 0..100) {list.append(i) // Does not trigger reallocation of space}
ArrayList 初始化 删除
使用remove方法指定位置删除
let list = ArrayList<String>(["a", "b", "c", "d"]) // list contains the elements "a", "b", "c", "d"
list.remove(1) // Delete the element at subscript 1, now the list contains elements "a", "c", "d"