53-HashMap
HashMap主要用来存储键值对数据, 是一种哈希表,提供对其包含的元素的快速访问。表中的每个元素都使用其键作为标识,可以使用键来访问相应的值。
HashMap 初始化
使用HashMap 之前需要先导包。
import std.collection.*
仓颉使用 HashMap<K, V>
表示 HashMap 类型,K 表示 HashMap 的键类型,K 必须是实现了 Hashable 和 Equatable<K>
接口
的类型,例如数值或 String。V 表示 HashMap 的值类型,V 可以是任意类型。
let a = HashMap<String, Int64>() // Created an empty HashMap whose key type is String and value type is Int64
let b = HashMap<String, Int64>([("a", 0), ("b", 1), ("c", 2)]) // whose key type is String and value type is Int64, containing elements ("a", 0), ("b", 1), ("c", 2)
let c = HashMap<String, Int64>(b) // Use another Collection to initialize a HashMap
let d = HashMap<String, Int64>(10) // Created a HashMap whose key type is String and value type is Int64 and capacity is 10
let e = HashMap<Int64, Int64>(10, {x: Int64 => (x, x * x)}) // Created a HashMap whose key and value type is Int64 and size is 10. All elements are initialized by specified rule function
HashMap 访问
HashMap 可以通过下标语法访问单个元素,也可以通过forin遍历所有元素,使用size获取HashMap 的长度。
-
下标语法访问的单个元素
let b = HashMap<String, Int64>([("a", 0), ("b", 1), ("c", 2)]) println(b['a']) // 0
-
forin语法访问所有元素
let map = HashMap<String, Int64>([("a", 0), ("b", 1), ("c", 2)]) for ((k, v) in map) { println("The key is ${k}, the value is ${v}") }
-
size获取长度
let b = HashMap<String, Int64>([("a", 0), ("b", 1), ("c", 2)]) println(b.size)
HashMap 增加
如果需要将单个键值对添加到 HashMap 里,请使用 put 函数。如果希望同时添加多个键值对,可以使用 putAll 函数。
let map = HashMap<String, Int64>()
map.put("a", 0) // map contains the element ("a", 0)
map.put("b", 1) // map contains the elements ("a", 0), ("b", 1)
let map2 = HashMap<String, Int64>([("c", 2), ("d", 3)])
map.putAll(map2) // map contains the elements ("a", 0), ("b", 1), ("c", 2), ("d", 3)
HashMap 修改
使用下标语法进行修改。
let map = HashMap<String, Int64>([("a", 0), ("b", 1), ("c", 2)])
map["a"] = 3
HashMap 删除
使用remove语法进行删除,需要指定删除的键。
let map = HashMap<String, Int64>([("a", 0), ("b", 1), ("c", 2), ("d", 3)])
map.remove("d") // map contains the elements ("a", 0), ("b", 1), ("c", 2)
HashMap contains
当想判断某个键是否被包含 HashMap 中时,可以使用 contains 函数。如果该键存在会返回 true,否则返回 false。
let map = HashMap<String, Int64>([("a", 0), ("b", 1), ("c", 2)])
let a = map.contains("a") // a == true
let b = map.contains("d") // b == false