Kotlin 笔记 集合

Kotlin中的集合明确区分了可变集合和不可变集合

List<T>只提供了sizeget这些只读的方法,MutableList<T>提供了修改List的方法。同样有Set<T>/MutableSet<T>Map<K, V>/MutableMap<K, V>

val numbers: MutableList<Int> = mutableListOf(1, 2, 3)
val readOnlyView: List<Int> = numbers
println(numbers)        // prints "[1, 2, 3]"
numbers.add(4)
println(readOnlyView)   // prints "[1, 2, 3, 4]"
readOnlyView.clear()    // -> does not compile

val strings = hashSetOf("a", "b", "c", "c")
assert(strings.size == 3)

创建集合的方法:

  • listOf
  • mutableListOf
  • setOf
  • mutableSetOf
  • mapOf(a to b, c to d)

list的toList方法返回当前list的快照

class Controller {
    private val _items = mutableListOf<String>()
    val items: List<String> get() = _items.toList()
}

List的一些其他方法


val items = listOf(1, 2, 3, 4)
items.first() == 1
items.last() == 4
items.filter { it % 2 == 0 }   // returns [2, 4]

val rwList = mutableListOf(1, 2, 3)
rwList.requireNoNulls()        // returns [1, 2, 3]
if (rwList.none { it > 6 }) println("No items above 6")  // prints "No items above 6"
val item = rwList.firstOrNull()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容