📜  kotlin list add - Kotlin (1)

📅  最后修改于: 2023-12-03 15:17:09.450000             🧑  作者: Mango

Kotlin List Add

Introduction

In Kotlin, a List is an ordered collection of elements that can be accessed using an index. This tutorial will guide you through the process of adding elements to a list in Kotlin.

Steps
  1. Create a new list using the listOf() function:
val list = listOf("item1", "item2", "item3")
  1. Create a mutable list using the mutableListOf() function if you need to modify the list later:
val mutableList = mutableListOf("item1", "item2", "item3")
  1. Add elements to the mutable list using the add() function:
mutableList.add("item4")
  1. Add elements to the mutable list at a specific index using the add(index: Int, element: E) function:
mutableList.add(2, "item5")
  1. Add all elements from another list to the mutable list using the addAll() function:
val anotherList = listOf("item6", "item7")
mutableList.addAll(anotherList)
  1. Check the modified list:
println(mutableList) // Output: [item1, item2, item5, item3, item4, item6, item7]
Conclusion

Congratulations! You have learned how to add elements to a list in Kotlin. Lists are essential data structures for storing and manipulating collections of items in your programs.