53

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?

Grokify
  • 13,266
  • 6
  • 50
  • 73
SadeQ digitALLife
  • 1,291
  • 4
  • 13
  • 19
  • 2
    Don't use `set` but `add.`. Also use the factory instead of constructor: `val list = mutableListOf()`. Also note I specified `val` instead of `var` (it has nothing to do with the list's mutability). – Marko Topolnik Jun 12 '18 at 10:41

2 Answers2

107

According to the api-doc:

val list = arrayListOf<Int>()

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

LuCio
  • 4,745
  • 2
  • 17
  • 31
38

I suggest you write

var myList: ArrayList<Int> = arrayListOf()
Szymon Chaber
  • 1,926
  • 15
  • 19