How To Add Element To List In Kotlin? - Tutorial Kart
Maybe your like
Kotlin List – Add Element
We can add element to a Mutable List only. An usual List is immutable. So, if we would like to add an element to given list, the list has to be a mutable list, otherwise, we may need to convert it to a mutable list and then add the element.
To add an element to a Mutable List in Kotlin, we can use add(element), or add(index, element) functions.
add(element) adds element to the end of this Mutable List.
add(index, element) adds element to this Mutable List at the given index.
Examples
In the following program, we will create a Mutable List with some integers, and then add some elements to it, using add(element) function.
Main.kt
</> Copy fun main(args: Array<String>) { val mutableList = mutableListOf(1, 3, 9, 16) mutableList.add(25) mutableList.add(36) mutableList.add(49) println(mutableList) }Output
[1, 3, 9, 16, 25, 36, 49]Now, let us use add(index, element) function and add an element 88 at index 2.
Main.kt
</> Copy fun main(args: Array<String>) { val mutableList = mutableListOf(1, 3, 9, 16, 25) mutableList.add(2, 88) println(mutableList) }Output
[1, 3, 88, 9, 16, 25]The original elements in the mutable list, from index=2, are shifted right.
Conclusion
In this Kotlin Tutorial, we learned how to add an element to a mutable list in Kotlin, using add() function, with the help of example programs.
Tag » Add Element List Kotlin
-
Collection Write Operations | Kotlin
-
Ajouter Des éléments à Une Liste Dans Kotlin - Techie Delight
-
How To Add An Item To A List In Kotlin? - Stack Overflow
-
How To Add Element To List At Specific Index In Kotlin? - Tutorial Kart
-
6 Ways To Add Items To A List In Kotlin - CodeVsColor
-
How To Add An Item To A List In Kotlin? - Tutorialspoint
-
Working With Lists In Kotlin - Baeldung
-
Kotlin Lists - Working With Lists In Kotlin - ZetCode
-
Add Element In Kotlin List Code Example - Code Grepper
-
Kotlin List & Mutable List Tutorial With Examples - BezKoder
-
Add Items To A List In Kotlin | Delft Stack
-
Shooting Yourself In The Foot While Adding An Element To A Kotlin List
-
Kotlin List : ListOf() - GeeksforGeeks
-
Kotlin Lists (listOf & MutableListOf): Explained With 16 Examples
-
Data Structures & Algorithms In Kotlin, Chapter 3: Linked List
-
Kotlin ArrayList - Javatpoint
-
How Mutable List Works In Kotlin With Examples? - EduCBA
-
What Is The dAll() Method In Kotlin?
-
How To Add New Element In Array In Kotlin ? - Tutorialwing