How to add one ArrayList to another? Strange output

Hello everyone, Can anyone help me in understanding the following code.

 val childArrayList : ArrayList<Int> = ArrayList()
 val parentArrayList : ArrayList<ArrayList<Int>> = ArrayList()

        for (i in 1..10){
            childArrayList.clear()
            childArrayList.add(i)
            parentArrayList.add(childArrayList)
        }

        for (x in parentArrayList){
            Log.d("confusion", x.toString())
        }

Output:

D/confusion: [10]
D/confusion: [10]

Only the final value is showing. Also only two values are printed although parentArrayList size is ten.
Thank you

List.add puts the reference of the value in the list. In your exemple, your child list is a single object / reference, that you erase each time.

To add a different value in parent list, you must stop re-using the same child array list, and create a new one each turn :

val parentArrayList = ArrayList<List<Int>>()

for (i in 1..10) parentArrayList.add(listOf(i))

parentArrayList.forEach { println(it) }
3 Likes

@alexis.manin

   val parentArrayList : ArrayList<ArrayList<Int>> = ArrayList()
        for (i in 1..10) { // This loop iterates only two times, why ?
            val childArrayList : ArrayList<Int> = ArrayList()
            for (j in 1..3) {
                childArrayList.add(j)
            }
            parentArrayList.add(childArrayList)
        }
        parentArrayList.forEach { println("confusion: $it") }

Output:

confusion: [1, 2, 3]
confusion: [1, 2, 3]

I need the above output ten times. Please help me.

I have tested your exact example in Kotlin playground, it prints 10 lines as expected.

Maybe there’s an issue with your local development environment ? Anyway, I cannot help you further, I have no clue about the problem.

I was confused when reading your question.
I expected [10] to be printed 10 times

But, after seeing your second example I think I know the issue

The issue might be your logging library for some reason not
printing your text 10 times. It might designed this way to
reduce repetitive output or it was taking time to print and the
process is killed/ended before it has time for that.

Anyway, you might try println instead and see if your problem is solved

If not, feel free to comment with extra details

4 Likes

@LSafer Thank you. Somehow you are right. I printed the values using Toast (in android), now its OK.

1 Like