Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficient copy an Array to another in Scala?

Tags:

arrays

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)
like image 973
BranY Avatar asked Sep 07 '15 05:09

BranY


People also ask

Can an array be copied to another array?

The System ClassarrayCopy(). This copies an array from a source array to a destination array, starting the copy action from the source position to the target position until the specified length. The number of elements copied to the target array equals the specified length.


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)
like image 112
Ionut Avatar answered Sep 17 '22 13:09

Ionut


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.

like image 21
tuxdna Avatar answered Sep 16 '22 13:09

tuxdna


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.

like image 26
elm Avatar answered Sep 17 '22 13:09

elm