可变与不可变集合

集合 - 图1

  • kotlin 集合底层也是调用 Java API
  • 不可变,不能添加和删除元素

集合创建

  1. val listOf:List<Int> = listOf(1, 2, 3)
  2. var mutableList:MutableList<Any> = mutableListOf(1, 2, 3)
  1. val map1 = mapOf("key" to "value", "name" to "july")
  2. var map2 = mutableMapOf("key" to "value", "name" to "july")

集合新增修改

  1. private fun testUpdateCollection() {
  2. var mutableList: MutableList<Any> = mutableListOf(1, 12, 3)
  3. mutableList.add(10)
  4. mutableList.remove(555)
  5. println(mutableList.joinToString())
  6. }

集合读取

  1. var mutableList: MutableList<Any> = mutableListOf(1, 12, 3)
  2. println(mutableList[2])
  3. mutableList[2]=20;

集合遍历

  1. private fun testIterateCollection() {
  2. val listOf: List<Int> = listOf(11, 22, 33)
  3. for (i in listOf) {
  4. println("for $i")
  5. }
  6. listOf.forEach {
  7. println("forEach = $it")
  8. }
  9. }

遍历带下标

  1. val listOf: List<Int> = listOf(11, 22, 33)
  2. for ((index, value) in listOf.withIndex()) {
  3. println("The element at $index is $value")
  4. }

输出:

  1. The element at 0 is 11
  2. The element at 1 is 22
  3. The element at 2 is 33

Pair

  1. private fun testPair() {
  2. var pair1 = Pair("a", "b")
  3. val pair2: Pair<String, Int> = "a" to 3
  4. println(pair1.first) //访问第1个参数
  5. println(pair1.second)//访问第2个参数
  6. val (key,value)=pair2 //解构
  7. }

Triple

    private fun testTriple() {
        var triple = Triple("a", "b",true)
        println(triple.first)
        println(triple.second)
        println(triple.third)
        val (one,two,three)=triple //解构
    }