溫馨提示×

kotlin中hashmap的用法是什么

小億
200
2024-03-26 19:19:15
欄目: 編程語言

在Kotlin中,HashMap是一種可變的集合,用于存儲(chǔ)鍵值對。以下是HashMap的基本用法示例:

// 創(chuàng)建一個(gè)空的HashMap
val hashMap = HashMap<String, Int>()

// 添加鍵值對
hashMap["key1"] = 1
hashMap["key2"] = 2
hashMap["key3"] = 3

// 獲取值
val value = hashMap["key1"]
println(value) // 輸出: 1

// 遍歷HashMap
for ((key, value) in hashMap) {
    println("Key: $key, Value: $value")
}

// 刪除鍵值對
hashMap.remove("key2")

// 檢查鍵是否存在
if (hashMap.containsKey("key2")) {
    println("Key 'key2' exists")
} else {
    println("Key 'key2' does not exist")
}

// 檢查值是否存在
if (hashMap.containsValue(3)) {
    println("Value '3' exists")
} else {
    println("Value '3' does not exist")
}

// 獲取HashMap的大小
val size = hashMap.size
println("HashMap size: $size")

HashMap可以存儲(chǔ)任意類型的鍵和值,可以方便地進(jìn)行插入、刪除、查找操作。在實(shí)際開發(fā)中,HashMap通常用于快速查找和存儲(chǔ)鍵值對。

0