Basically, this code works:
var optionsList = ArrayList<String>()
optionsList.add("Alpha")
optionsList.add("Bravo")
optionsList.add("Charlie")
optionsList[2] = "Foxtrot"// Assignment works (only) if initialization has been done previously through add()
However, the following makes the application crash (with no compile time errors or warnings):
var optionsList = ArrayList<String>(3)
optionsList[0] = "Alpha"
optionsList[1] = "Bravo"
optionsList[2] = "Charlie"
This seems unexpected and I can't figure out the reason for the crash. In my understanding, both ways should be equivalent - in the first we are allocating memory for and initializing only one element at a time, whereas in the second we are allocating the memory for all elements together at the beginning and later changing values.
Can someone please help me understand what might be going on under the hood here? I have only just started learning Kotlin and have used C++ in the past, so that might be affecting how I am thinking about this.
set()(overloaded operator for[n] =) can only be used to replace value, not to add new values. It throws IndexOutOfBoundException if there is no element at specified index geeksforgeeks.org/arraylist-set-method-in-java-with-examples