51-ArrayList

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 初始化

需要先导入。

typescript 复制代码
import std.collection.*

ArrayList支持多种初始化方式

typescript 复制代码
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 初始化 访问

支持直接使用下标进行访问。

typescript 复制代码
let c = ArrayList<Int64>([0, 1, 2])
println(c[1])

通过size访问列表的长度。

typescript 复制代码
println(c.size)

可以通过forin访问列表内的所有成员。

typescript 复制代码
let list = ArrayList<Int64>([0, 1, 2])
for (i in list) {
    println("The element is ${i}")
}

ArrayList 初始化 修改

可以通过下标直接修改

typescript 复制代码
let list = ArrayList<Int64>([0, 1, 2])
list[0] = 3

ArrayList 初始化 增加

在列表末尾增加元素使用append 和appendAll ,在指定位置插入元素使用insert 和insertAll

typescript 复制代码
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, 3


let list = ArrayList<Int64>([0, 1, 2]) // list contains elements 0, 1, 2
list.insert(1, 4) // list contains elements 0, 4, 1, 2

如果知道大约需要添加多少个元素,可以在添加之前预备足够的内存以避免中间重新分配,这样可以提升性能表现。

typescript 复制代码
    let list = ArrayList<Int64>(100) // Allocate space at once
    for (i in 0..100) {
        list.append(i) // Does not trigger reallocation of space
    }
    list.reserve(100) // Prepare more space
    for (i in 0..100) {
        list.append(i) // Does not trigger reallocation of space
    }

ArrayList 初始化 删除

使用remove方法指定位置删除

typescript 复制代码
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"
相关推荐
特立独行的猫a5 分钟前
用仓颉写桌面应用:从 npx 建工程到串口实时示波器
开源·harmonyos·tauri·仓颉·cj-tarui
特立独行的猫a2 天前
仓颉语言实现强大的Modbus调试工具Modbus Poll:cj-tauri项目介绍与实战
harmonyos·tauri·modbus·仓颉·modbus poll
特立独行的猫a6 天前
用仓颉语言给娃写了个打字练习游戏:cj-tauri 项目实战
游戏·ui·框架·tauri·仓颉·cangjie·cj-tauri
特立独行的猫a11 天前
用仓颉写一个 Tauri:IPC 的每次往返实现原理(web层到仓颉层的触发过程)
前端·ui·harmonyos·tauri·鸿蒙·仓颉
特立独行的猫a1 个月前
仓颉语言开发踩坑记录--基于仓颉语言实现的 Harness实战
ai·agent·仓颉·cangjie·harness
特立独行的猫a1 个月前
仓颉语言原生 Coding Agent:cjh · 仓颉语言实现的 Harness
ai·agent·harmonyos·仓颉·cangjie·harness