深色模式
Kotlin 集合之 创建集合的方式
使用元素创建集合
创建集合常用的方式,是使用官方库提供的函数:
listOf<T>()、mutableListOf<T>():
kotlin
val list1 = listOf("one", "two", "three")
val list2 = listOf<String>()
val list3 = mutableListOf(1, 2, 3)
val list4 = mutableListOf<Int>()setOf<T>()、mutableSetOf<T>():
kotlin
val list1 = listOf("one", "two", "three")
val list2 = listOf<String>()
val list3 = mutableListOf(1, 2, 3)
val list4 = mutableListOf<Int>()mapOf<T>()、mutableMapOf<T>():
kotlin
val map1 = mapOf("one" to 1, "two" to 2)
val map2 = mapOf(Pair("one", 1), Pair("two", 2))
val map3 = mutableMapOf<String, Int>()注意,每个to操作符会创建一个Pair对象,上面的map1、map2方式对内存不友好,应该优先使用下面的等效方式:
kotlin
val map4 = mutableMapOf<String, Int>().apply {
this["one"] = 1
this["two"] = 2
}
// 或
val map5 = mutableMapOf<String, Int>().apply {
put("one", 1)
put("two", 2)
}使用 builder 函数创建集合
使用buildList()、buildSet()、buildMap()函数,返回的是只读集合。这种方式不是很常用。
kotlin
val list = buildList {
add("one")
add("two")
add("three")
}
val set = buildSet {
add(1)
add(2)
add(3)
}
val map = buildMap {
put("one", 1)
put("two", 2)
}创建空集合
创建空集合的函数:emptyList()、emptySet()、emptyMap()。
kotlin
val empty = emptyList<String>()带初始化的方式创建 List
List 有一个带函数参数的构造函数List(size: Int, init: (index: Int) -> T): List<T>
用法举例:
kotlin
val list = List(5, { it * 2 })
println(list)
// [0, 2, 4, 6, 8]另外还有MutableList(size: Int, init: (index: Int) -> T): MutableList<T>,用法同上。
使用具体类型的构造函数来创建集合
使用集合类的构造函数:
kotlin
val linkedList = LinkedList<String>(listOf("one", "two", "three"))
val presizedSet = HashSet<Int>(32)使用复制来创建集合
集合复制相关函数toList(), toMutableList(), toSet()等,都是浅拷贝(shallow copy)。
使用集合操作符创建集合
某些符合操作符会创建出一个新的集合
