可变与不可变集合
- kotlin 集合底层也是调用 Java API
- 不可变,不能添加和删除元素
集合创建
val listOf:List<Int> = listOf(1, 2, 3)
var mutableList:MutableList<Any> = mutableListOf(1, 2, 3)
val map1 = mapOf("key" to "value", "name" to "july")
var map2 = mutableMapOf("key" to "value", "name" to "july")
集合新增修改
private fun testUpdateCollection() {
var mutableList: MutableList<Any> = mutableListOf(1, 12, 3)
mutableList.add(10)
mutableList.remove(555)
println(mutableList.joinToString())
}
集合读取
var mutableList: MutableList<Any> = mutableListOf(1, 12, 3)
println(mutableList[2])
mutableList[2]=20;
集合遍历
private fun testIterateCollection() {
val listOf: List<Int> = listOf(11, 22, 33)
for (i in listOf) {
println("for $i")
}
listOf.forEach {
println("forEach = $it")
}
}
遍历带下标
val listOf: List<Int> = listOf(11, 22, 33)
for ((index, value) in listOf.withIndex()) {
println("The element at $index is $value")
}
输出:
The element at 0 is 11
The element at 1 is 22
The element at 2 is 33
Pair
private fun testPair() {
var pair1 = Pair("a", "b")
val pair2: Pair<String, Int> = "a" to 3
println(pair1.first) //访问第1个参数
println(pair1.second)//访问第2个参数
val (key,value)=pair2 //解构
}
Triple
private fun testTriple() {
var triple = Triple("a", "b",true)
println(triple.first)
println(triple.second)
println(triple.third)
val (one,two,three)=triple //解构
}