Copying arrays

When assigning one array to another, Kotlin does not create a new copy in memory. Instead, both instances of the array point to the same location. When the source array is assigned to the target array, both arrays will be impacted if either is updated. To understand this problem, take a look at the following example:

  1. Create an integer array, source, and assign it to a target array.
  2. Print the target array on the screen.
  3. Update the first element of the source array and print the target array. Notice that both arrays affect each other and that both arrays share the same memory location:
fun arrayInstance01(){

val source = intArrayOf(1,2,3)
val target = source

// print target
for (element in target){
println(element)
}

// update source
source.set(0,10)

// print target
for (element in target){
println(element)
}

if(source === target){
println("pointing to the same memory location")
}
}

If we want an independent instance of an array, we need to create a new array and copy each element of the source array:

  1. Create a target array that is the same size as the source array and use a for loop to copy each element.
  2. Update the source array and verify that it does not affect the target array:
fun arrayInstance02(){

val source = intArrayOf(1,2,3)
val target = IntArray(source.size)

for (i in 0 until source.size){
target[i] = source[i]
}

// update source
source.set(0,10)

// print target
for (element in target){
println(element)
}

if(source !== target){
println("pointing to different memory location")
}
}

Kotlin also provides a copyOf() function to create a new instance of an array:

fun copyArray(){

val source = intArrayOf(1,2,3)
val target = source.copyOf()

// update source
source.set(0,10)
if(source !== target){
println("pointing to different memory location")
}

for (element in target) {
println(element)
}
}

The copyOf function creates an independent array of the same type. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.237.201