Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an empty array list in Kotlin? [duplicate]

I have an empty array list:

var mylist: ArrayList<Int> = ArrayList() 

When I want to set value in it I got this error:

java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 

The question is: How can I initialize my list?

like image 656
SadeQ digitALLife Avatar asked Jun 12 '18 10:06

SadeQ digitALLife


People also ask

How do you make an ArrayList empty in Kotlin?

The clear() function of ArrayList class is used to remove (clear) all the elements of list. For example: fun main(args: Array<String>){ val arrayList: ArrayList<String> = ArrayList<String>(5)

How do you declare and initialize an ArrayList in Kotlin?

Initializing an ArrayList by Conversion From that array, we can obtain an ArrayList using the toCollection() method and passing an empty ArrayList. The toCollection() method then populates the ArrayList with all the values in the array.


2 Answers

According to the api-doc:

val list = arrayListOf<Int>() 

This is also mentioned here: How to initialize List in Kotlin? .

like image 72
LuCio Avatar answered Sep 22 '22 11:09

LuCio


I suggest you write

var myList: ArrayList<Int> = arrayListOf() 
like image 42
Szymon Chaber Avatar answered Sep 19 '22 11:09

Szymon Chaber