1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| //遍历List var list1 = listOf("Java", null, "Kotlin", "Go") list1.forEach { println(it) } for (str in list1) { println(str) } for (i in list1.indices) { println(list1[i]) println("get = ${list1.get(i)}") println("elementAt = ${list1.elementAt(i)}") } var index = list1.indexOf("Go") println("Go 在数组中的位置:${index}")//3
var list2 = mutableListOf(1, 2, 3, 1, 8, 3, 4, 6, 1, 4, 2, 3) //最后一次出现的的位置 var last1 = list2.lastIndexOf(2)//10 //最后一次出现的的位置 var last2 = list2.indexOfLast { it == 2 }//10 //第一次出现的位置 var first = list2.indexOfFirst { it == 2 }//1 println("2在数组中第一次出现在${first},最后一次出现在${last1},${last2}") //返回集合 var list3 = listOf("Java", null, "Kotlin", "PHP", null, "Go") var sublist = list3.subList(2, 5)//从第2个到第5个之间的元素 println(sublist.toString())//[Kotlin, PHP, null] // var list4 = mutableListOf("Java", "JavaScript", null, "HTML", "Kotlin", null, "Python", "PHP", "Go") var list4 = mutableListOf("Java", null, "HTML", "Go") println(list4)//[Java, null, HTML, Go] //新增 list4.add("Python") list4.add(2, "C++") list4.addAll(listOf("Kotlin", null)) println(list4)//[Java, null, C++, HTML, Go, Python, Kotlin, null] //删除 list4.removeAt(1) println(list4)//[Java, C++, HTML, Go, Python, Kotlin, null] //list4[6] ="CSS"; list4.set(6, "CSS") println(list4)//[Java, C++, HTML, Go, Python, Kotlin, CSS] list4.remove("Go") println(list4)//[Java, C++, HTML, Python, Kotlin, CSS] list4.add(3, "Go") list4.add(5, "Go") println(list4)//[Java, C++, HTML, Go, Python, Go, Kotlin, CSS] //替换元素 list4.replaceAll { if (it.equals("Go")) { "go" } else { it } } println(list4)//[Java, C++, HTML, go, Python, go, Kotlin, CSS] //删除 list4.removeAll(listOf("go")) println(list4)//[Java, C++, HTML, Python, Kotlin, CSS]
//清空 list4.clear() println(list4)//[]
|