How to efficiently copy an array in Scala?

How can I use another method to copy Arrayto another Array?

I thought of using a statement =. For example:

val A = Array(...)
val B = A

But it normal?

The second way is to use for loop, for example:

val A = Array(...)
val B = new Array[](A.length)//here suppose the Type is same with A
for(i <- 0 until A.length)
    B(i) = A(i)
+4
source share
3 answers

you can use .clone

scala> Array(1,2,3,4)
res0: Array[Int] = Array(1, 2, 3, 4)

scala> res0.clone
res1: Array[Int] = Array(1, 2, 3, 4)
+12
source

Consider Array.copyin this example where destis mutable Array,

val a = (1 to 5).toArray
val dest = new Array[Int](a.size)

and therefore

dest
Array[Int] = Array(0, 0, 0, 0, 0)

Then for

Array.copy(a, 0, dest, 0, a.size)

we have that

dest
Array[Int] = Array(1, 2, 3, 4, 5)

From the Scala API array, the Scala note is Array.copyequivalent to Java System.arraycopywith support for polymorphic arrays.

+4
source

- map identity :

scala> val a = Array(1,2,3,4,5)
a: Array[Int] = Array(1, 2, 3, 4, 5)

scala> val b = a map(identity)
b: Array[Int] = Array(1, 2, 3, 4, 5)

scala> b(0) = 6

scala> a == b
res8: Boolean = false

scala> a
res9: Array[Int] = Array(1, 2, 3, 4, 5)

scala> b
res10: Array[Int] = Array(6, 2, 3, 4, 5)

, Array.

+4
source

Source: https://habr.com/ru/post/1606200/


All Articles