如何在 Kotlin 中初始化 List


List<T> 表示通用数据类型的 List 集合。通过 <T>,我们理解到 List 没有具体的取值类型。我们来看看如何在 Kotlin 中初始化这样一个集合。

List<T> 可以分为两种类型:不可变可变。我们将看到初始化 List<T> 的两种不同的实现。

示例 - 初始化 List<T> ~ 不可变 List

一旦列表被声明为不可变,那么它就变为只读。

fun main(args: Array<String>) {
   var myImmutableList = listOf(1, 2, 3)

   // Convert array into mutableList
   // Then, add elements into it.
   myImmutableList.toMutableList().add(4)

   // myImmutableList is not a mutable List
   println("Example of Immutable list: " + myImmutableList)
}

输出

在这个示例中,我们声明了一个不可变列表,称为“myImmutableList”,然后在其中添加了一个值后对它进行了打印。

Example of Immutable list: [1, 2, 3]

示例 - 初始化 List<T> ~ 可变 List

我们可以修改可变列表的值。以下示例展示了如何初始化一个可变列表。

fun main(args: Array<String>) {
   val myMutableList = mutableListOf(1, 2, 3)
   myMutableList.add(4)
   println("Example of mutable list: " + myMutableList)
}

输出

它将产生以下输出 -

Example of mutable list: [1, 2, 3, 4]

更新于: 2022-03-16

724 次查看

开启你的职业生涯

通过完成课程来获得认证

开始
广告
© . All rights reserved.