如何在 Kotlin 中向 ArrayList 添加元素?
在本例中,我们将了解如何在 Kotlin 中定义 ArrayList 并在列表中添加元素。我们可以使用库函数 **add()** 或 **"+="** 运算符来实现。为了演示,我们将创建两个 ArrayList,一个是 **可变** 类型,另一个是 **不可变** 类型。
示例 – 使用 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) // Convert array to mutableList using toMutableList() method // Then, insert element into it var myImmutableList = listOf(1, 2, 3) myImmutableList.toMutableList().add(4) // myImmutableList is not a mutable List println("Example of Immutable list: " + myImmutableList) }
输出
它将产生以下输出:
Example of mutable list: [1, 2, 3, 4] Example of Immutable list: [1, 2, 3]
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例 – 使用 "+=" 运算符添加元素
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]
广告