在Kotlin中,你可以通过使用Map 类作为变量的类型来创建一个字典。
要创建一个Map 类的实例,你可以调用mapOf() 函数,并将键值对作为其参数传递。
下面是一个创建字典的例子,键的类型是String ,值的类型是Int :
val dictionary = mapOf("key" to 1, "anotherKey" to 2)
println(dictionary) // {key=1, anotherKey=2}
你可以通过在索引操作符中指定键来获得字典的单个值。
例如,要抓取key 的值:
print(dictionary["key"]) // 1
创建一个可变的地图
Map 类是不可变的。这意味着你不能在初始化后修改或添加更多的键值对。
在下面的例子中,将另一个值赋给现有的键并添加一个新的键值对会触发一个错误:
val dictionary = mapOf("key" to 1, "anotherKey" to 2)
dictionary["key"] = 20 // Error: not set method providing array access
dictionary["max"] = 99 // Error: not set method providing array access
要创建一个可变的 dictionary,需要使用MutableMap 类作为 dictionary 的蓝本。
MutableMap 实例可以通过调用mutableMapOf() 函数来创建。
它接受与mapOf() 函数相同的 key-value 参数:
val mutableDict = mutableMapOf("key" to 1, "anotherKey" to 2)
mutableDict["key"] = 20
mutableDict["max"] = 99
println(mutableDict) // {key=20, anotherKey=2, max=99}
MutableMap 类扩展了Map 类,并为它增加了写操作方法。
MutableMap 类也有两个子类:
LinkedHashMap类保留了键值对的插入顺序。HashMap类并不保证键值对的插入顺序。
LinkedHashMap 实例可以使用linkedMapOf() 函数来创建,而HashMap 实例可以使用hashMapOf() 函数来创建。
下面是一个创建HashMap 词典的例子:
val mutableDict = hashMapOf("key" to 1, "anotherKey" to 2)
mutableDict["key"] = 20
mutableDict["max"] = 99
// 👇 The order of the pairs are random
print(mutableDict) // {anotherKey=2, max=99, key=20}
现在你已经学会了如何用Kotlin创建一个字典。干得好!👍