简体   繁体   中英

Kotlin returns 2d Array property as reference

I was messing around with Kotlin and 2d arrays an I detected a strange behavior that I don't understand. So I have a Class that has a 2d Array as property and I have another class that takes that Array and change it. But now the original Array from the property has changed.

My code looks like that

import org.junit.Test

class ClassHasArray {
    val someArray = Array(3) { BooleanArray(3) }
}

class ClassWantsArray {

    @Test
    fun test(){
        val c = ClassHasArray()
        val arr = c.someArray
        arr[1][1] = true
        printArray(c.someArray)
    }

    private fun printArray(array: Array<BooleanArray>){
        for (i in array.indices) {
            println(array[i].contentToString())
        }
    }
}

The output of the Test is

[false, false, false]
[false, true, false]
[false, false, false]

But I was expecting

[false, false, false]
[false, false, false]
[false, false, false]

because I didn't changed the property from the class ClassHasArray

So for me it looks like c.someArray is returning the reference of the property. Is there a way to prevent this? I just want a copy to work with, without messing up my property.

You need to make a copy of c.someArray and also a copy of all elements of that array because those elements are also BooleanArrays, so you can do this by changing this declaration val arr = c.someArray to this:

val arr = Array(c.someArray.size) { c.someArray[it].copyOf() }

With this approach we are going to create a new array containing a copy of the elements of c.someArray

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM