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

在列表末尾增加元素使用appendappendAll ,在指定位置插入元素使用insertinsertAll

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"
相关推荐
We....8 天前
仓颉函数:定义、调用与进阶特性
函数·仓颉
We....11 天前
仓颉语言入门:核心概念与基础数据类型
编程语言·仓颉·仓颉鸿蒙
_waylau15 天前
跟老卫学仓颉编程语言开发:浮点类型
人工智能·华为·harmonyos·鸿蒙·鸿蒙系统·仓颉
坚果的博客18 天前
cjman:仓颉生态的轻量化工程管理工具
仓颉
_waylau22 天前
跟老卫学仓颉编程语言开发:整数类型
算法·华为·harmonyos·鸿蒙·鸿蒙系统·仓颉
_waylau1 个月前
首本鸿蒙架构师培养手册《鸿蒙架构师修炼之道》简介
华为·harmonyos·鸿蒙·鸿蒙系统·仓颉·cangjie
星空下的月光影子2 个月前
text_encoding4cj 仓颉三方库实战教程
文件处理·仓颉
长弓三石2 个月前
鸿蒙网络编程系列60-仓颉版TLS客户端示例
网络·harmonyos·鸿蒙·仓颉
superman超哥2 个月前
仓颉并发调试利器:数据竞争检测的原理与实战
开发语言·仓颉编程语言·仓颉
superman超哥2 个月前
仓颉元编程进阶:编译期计算能力的原理与深度实践
开发语言·后端·仓颉编程语言·仓颉·仓颉语言·仓颉元编程·编译器计算能力