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)
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.
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)
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With