欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > 51-ArrayList

51-ArrayList

2025/2/21 10:52:11 来源:https://blog.csdn.net/u013176440/article/details/145603655  浏览:    关键词:51-ArrayList

51-ArrayList

Collection 类型介绍

仓颉中常用的几种基础 Collection 类型,包含 Array、ArrayList、HashSet、HashMap。

可以在不同的场景中选择适合对应业务的类型:

  • Array:如果不需要增加和删除元素,但需要修改元素,就应该使用它。
  • ArrayList:如果需要频繁对元素增删查改,就应该使用它。
  • HashSet:如果希望每个元素都是唯一的,就应该使用它。
  • HashMap:如果希望存储一系列的映射关系,就应该使用它。

下表是这些类型的基础特性:

类型名称元素可变增删元素元素唯一性有序序列
Array<T>YNNY
ArrayList<T>YYNY
HashSet<T>NYYN
HashMap<K, V>K: N, V: YYK: Y, V: NN

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

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

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"

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词