The question I want to ask is about programming related question in kotlin. This question may seem really bad , but I can't think how to handle this situation.
val array = ArrayList<ArrayList<Int>>()
val subAnswer = ArrayList<Int>()
subAnswer.add(1)
subAnswer.add(2)
subAnswer.add(3)
array.add(subAnswer)
subAnswer.clear()
If I printed out the array , it is empty . The behaviour I have expected is subAnswer is cleared but the array will contain [[1,2,3]] I want to know why. Isn't it supposed to contained [[1,2,3]] ? Why clearing subAnswer also cleared the array? And how can it be solved?
I thought an object was copied and added to the array so the added object to array and subAnswer doesn't share the same memory address. In this case , it seems like the added object is just a reference of the subAnswer so clearing subAnswer can also affect the array.
If I want to get the expected behavior, how can I do it ? If there's any programming concept related blogs about this problem , please let me know it. Thank you.
At first you've added a reference of an array contained in subAnswer to variable array and then cleared values in that reference.
Since they were the same reference in the heap, changing it from one variable changes it.
To preserve the list, you can make a duplicate of it,
array.add(ArrayList(subAnswer)) // <- creates a new ArrayList with elements from subAnswer
subAnswer.clear()
PS: Using ArrayList directly is not a recommended style in Kotlin, you should use MutableList instead.
val list = mutableListOf<List<Int>>() // or use MutableList instead if you like too use
val subAnswer = mutableListOf<Int>()
subAnswer.add(1)
subAnswer.add(2)
subAnswer.add(3)
list.add(subAnswer.toList()) // copies and create new list, or use toMutableList to create a mutable list
subAnswer.clear()