How to add an item to an ArrayList
in Kotlin?
To add a single element to a list or a set, use the add() function. The specified object is appended to the end of the collection. addAll() adds every element of the argument object to a list or a set.
Kotlin arrayListOf() Example 4 - get()The get() function of arrayListOf() is used to retrieve the element present at specified index. For example: fun main(args: Array<String>){ val list: ArrayList<String> = arrayListOf<String>()
Using add() function The standard solution to prepend an element to the front of a list, you can use the add() function with the specified index as 0. You can easily extend the solution to add multiple elements to the front of the list.
For people just migrating from java
, In Kotlin
List
is by default immutable and mutable version of Lists is called MutableList
.
Hence if you have something like :
val list: List<String> = ArrayList()
In this case you will not get an add()
method as list is immutable. Hence you will have to declare a MutableList
as shown below :
val list: MutableList<String> = ArrayList()
Now you will see an add()
method and you can add elements to any list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With