How to efficient copy an Array to another in Scala

2020-03-20 08:26发布

问题:

How I can use another way to copy a Array to another Array?

My thought is to use the = operator. For example:

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

But this is okay?

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)

回答1:

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)


回答2:

The shortest and an idiomatic way would be to use map with identity like this:

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

Make a copy

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

Modify copy

scala> b(0) = 6

They seem different

scala> a == b
res8: Boolean = false

And they are different

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

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

This copy would work with all collection types, not just Array.



回答3:

Consider Array.copy in this example where dest is a mutable Array,

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

and so

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 Scala Array API note Scala Array.copy is equivalent to Java System.arraycopy, with support for polymorphic arrays.



回答4:

Another option is to create the new array, B, using A as a variable argument sequence:

val B = Array(A: _*)

The important thing to note is that using the equal operator, C = A, results in C pointing to the original array, A. That means changing C will change A:

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

scala> val B = Array(A: _*)
B: Array[Int] = Array(1, 2, 3, 4)

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

scala> B(0) = 9

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

scala> B
res2: Array[Int] = Array(9, 2, 3, 4)

scala> C(0) = 8

scala> C
res4: Array[Int] = Array(8, 2, 3, 4)

scala> A
res5: Array[Int] = Array(8, 2, 3, 4)


标签: arrays scala