How to initialize an empty array list in Kotlin?

ArraylistKotlinIndexoutofboundsexception

Arraylist Problem Overview


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?

Arraylist Solutions


Solution 1 - Arraylist

According to the api-doc:

val list = arrayListOf<Int>()

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

Solution 2 - Arraylist

I suggest you write

var myList: ArrayList<Int> = arrayListOf()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSadeQ digitALLifeView Question on Stackoverflow
Solution 1 - ArraylistLuCioView Answer on Stackoverflow
Solution 2 - ArraylistSzymon ChaberView Answer on Stackoverflow