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?
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)
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.
According to the api-doc:
val list = arrayListOf<Int>()
This is also mentioned here: How to initialize List in Kotlin? .
I suggest you write
var myList: ArrayList<Int> = arrayListOf()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With