How To Add Element To List At Specific Index In Kotlin? - Tutorial Kart
Maybe your like
Kotlin List – Add Element at Specific Index
To add an element to a Mutable List at specific index in Kotlin, we can use add(index, element) function.
add(index, element) adds the element to this Mutable List at given index.
Examples
In the following program, we will create a Mutable List with some integers, and then add an element 88 at index 2, using add(element, index) function.
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]If the index is greater than the size of the list, then add() function throws java.lang.IndexOutOfBoundsException.
In the following program, the size of the list is five, but let us try to add the element at index 7.
Main.kt
</> Copy fun main(args: Array<String>) { val mutableList = mutableListOf(1, 3, 9, 16, 25) mutableList.add(7, 88) println(mutableList) }Output
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 7, Size: 5 at java.base/java.util.ArrayList.rangeCheckForAdd(ArrayList.java:788) at java.base/java.util.ArrayList.add(ArrayList.java:513) at MainKt.main(Main.kt:3)Conclusion
In this Kotlin Tutorial, we learned how to add an element at given index 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 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