Make an ArrayList whose attributes have ArrayList too

Kelvin Herwanda Tandrio :

I have a problem to make data ArrayList whose attributes have ArrayList too. The model data looks like this code.

data class DataArrayInArray02(
    val no: Int? = null,
    val dataArray: ArrayList<Int>
)

I want to get a data DataArrayInArray02 like this. Result 1: Get data DataArrayInArray02

This is my code

fun main() {
    val dataArrayInArray = ArrayList<DataArrayInArray02>()
    val dataChildrenArray = ArrayList<Int>()

    for (i in 0..3) {
        val data = (0..10).random()
        for (j in 0..data) {
            val d = (1..1000).random()
            dataChildrenArray.add(d)
        }
        dataArrayInArray.add(DataArrayInArray02(i+1, dataChildrenArray))
        println("ID : ${dataArrayInArray[i].no}, Data : ${dataArrayInArray[i].dataArray}")
        dataChildrenArray.clear()
    }
}

When I run this code, I get the result like the picture above.

I call dataArrayInArray using looping "for" looks like this.

for (j in 0 until dataArrayInArray.size) {
        println("ID : ${dataArrayInArray[j].no}, Data : ${dataArrayInArray[j].dataArray}")
    }

But, I get the result like this.

Result 2: Get Empty Data for Attribute dataArray

So, which code is incorrect? Is it because of using dataChildrenArray.clear()? If I delete that code. The result will get like this:

ID : 1, Data : [915, 565, 591, 254, 67]
ID : 2, Data : [915, 565, 591, 254, 67, 258, 57, 767, 866, 986, 558, 187, 976]

where ID 2 should only display data [258, 57, 767, 866, 986, 558, 187, 976].

How to solve that problem?

Tenfour04 :

You're passing the same instance of an ArrayList<Int> to each instance of DataArrayInArray02 in the top level list. To fix your code, move the line

val dataChildrenArray = ArrayList<Int>()

inside your for loop so a new one is created for each child.

If you're OK with using List instead of ArrayList, you could simplify this:

val dataArrayInArray = (1..4).map { i ->
        val innerListSize = (0..10).random()
        val innerList = (0..innerListSize).map { (1..1000).random() }
        DataArrayInArray02(i, innerList)
    }

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=398548&siteId=1