如何在 Kotlin 中向 ArrayList 添加项目?

kotlin mobile developmentapps/applications

在本例中,我们将了解如何在 Kotlin 中定义 ArrayList 并在列表中添加项目。我们可以使用库函数 add() 或 "+=" 运算符来实现。为了演示,我们将创建两个 ArrayList,一个是 mutable 类型,另一个是 immutable 类型。

示例 - 使用 add() 插入新项目

我们可以使用 Kotlin 库提供的 add() 函数向 ArrayList 插入项目。在此示例中,我们将创建两个列表:一个是 "myMutableList",它是可变数据类型的集合;另一个是 "myImmutableList",它是不可变数据类型的集合。

我们不能直接在不可变集合上使用 add()。为了使用 add() 函数,我们需要先使用 toMutableList() 函数将不可变列表转换为可变列表,然后再在其中应用 add()。

fun main(args: Array<String>) {
   val myMutableList = mutableListOf(1, 2, 3)
   myMutableList.add(4)
   println("Example of mutable list: " + myMutableList)
   
   // 使用 toMutableList() 方法将数组转换为可变列表
   // 然后,将元素插入其中
   var myImmutableList = listOf(1, 2, 3)
   myImmutableList.toMutableList().add(4)
   
   // myImmutableList 不是可变列表
   println("Example of Immutable list: " + myImmutableList)
}

输出

它将产生以下输出 −

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

示例 - 使用"+="运算符添加项目

Kotlin 提供了另一个运算符"+="来将项目添加到列表中。此运算符适用于可变和不可变数据类型。我们将使用"+="运算符修改上述示例。

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

输出

它将产生以下输出 −

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

相关文章