64

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?

1
  • 2
    Don't use set but add.. Also use the factory instead of constructor: val list = mutableListOf<Int>(). Also note I specified val instead of var (it has nothing to do with the list's mutability). Commented Jun 12, 2018 at 10:41

2 Answers 2

133

According to the api-doc:

val list = arrayListOf<Int>()

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

Sign up to request clarification or add additional context in comments.

2 Comments

Isn't an arrayList different from an array in kotlin?
@SMBiggs See SO Q&A
47

I suggest you write

var myList: ArrayList<Int> = arrayListOf()

3 Comments

val myList = arrayListOf<Int>() reads much better.
What if it's an array, not an arrayList?
you can do this with val value= Array(20) { 0 }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.