Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an item to an ArrayList in Kotlin?

How to add an item to an ArrayList in Kotlin?

like image 581
Ramesh Avatar asked Sep 15 '17 08:09

Ramesh


People also ask

How do I add items to a list on 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.

How do I access an ArrayList in Kotlin?

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>()

How do I add items to my list on first position Kotlin?

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.


1 Answers

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.

like image 188
Tarun Deep Attri Avatar answered Oct 07 '22 06:10

Tarun Deep Attri