Home > Back-end >  Kotlin: adding a mutable list into 2D mutable list duplicate it's previous lists to the newly a
Kotlin: adding a mutable list into 2D mutable list duplicate it's previous lists to the newly a

Time:09-17

I have 2 mutable lists

val line = mutableListOf<String>()
val minesField = mutableListOf<MutableList<String>>()

the aim of these 2 lists is to create a table of content made of X and 0 (9*9).

I have a function that creates the content of the line and at the end I add it to the minesField mutablelist. i tried to add it in several ways but all ended in the same result.

       minesField.add(line)
        minesField  = line
        minesField.addAll(listOf(line))

what happens is that the last line i add to minesField duplicates itself into all previously added lines/lists before. therefore at the end, i get a table of 9 duplicate lines to the last line i added.

i thought that this shouldn't happen since the function = .add() creates a new index for the newly added list/line only. it doesn't duplicate it all over the whole list...

how this can be solved?

CodePudding user response:

I assume you perform minesField.add(line) repeatedly using exactly the same line object.

The point is: minesField.add(line) does not copy the contents of line into minesField. It adds the line object itself to it. If you then modify line you will modify the contents of minesField as well. As a result, you end up with minesField that contains 9 references to exactly the same line object.

You need to either create a new line object with each new line or you need to create a copy before adding to minesField by using: line.toList().

CodePudding user response:

You said:

i thought that this shouldn't happen since the function = .add() creates a new index for the newly added list/line only.

That is correct. However, the new element points to the same line object as all the other elements, because you are using a single object for all lines. So this, for example:

minesField.add(line)
minesField.add(line)

causes minesField to be a list of two references to the same list (same as the list object that line refers to).

One way to make each line refer to a unique object and avoid duplication is to add a copy of line each time:

minesField.add(line.toMutableList())
  • Related