60

I have an empty arraylist:

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?

SadeQ digitALLife
  • 1,403
  • 4
  • 16
  • 22
  • 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

128

According to the api-doc:

val list = arrayListOf<Int>()

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

LuCio
  • 5,055
  • 2
  • 18
  • 34
  • 1
    Isn't an arrayList different from an array in kotlin? – SMBiggs Mar 28 '20 at 06:05
  • @SMBiggs See SO [Q&A](https://stackoverflow.com/questions/76051010/what-is-the-difference-between-array-list-and-arraylist-in-kotlin) – LuCio Aug 18 '23 at 08:32
44

I suggest you write

var myList: ArrayList<Int> = arrayListOf()
Szymon Chaber
  • 2,076
  • 16
  • 19