BranY
BranY

Reputation: 173

How to efficient copy an Array to another in Scala?

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)

Upvotes: 11

Views: 19307

Answers (4)

Patrick Pisciuneri
Patrick Pisciuneri

Reputation: 51

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)

Upvotes: 3

elm
elm

Reputation: 20435

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.

Upvotes: 7

tuxdna
tuxdna

Reputation: 8487

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.

Upvotes: 10

Ionut
Ionut

Reputation: 486

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)

Upvotes: 25

Related Questions