11

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
  • i want to konw , if there has another way to deal with this ? Commented Sep 7, 2015 at 5:37

4 Answers 4

25

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)
Sign up to request clarification or add additional context in comments.

1 Comment

While this is correct, I can think of very few reasons why someone would want to create a duplicate of an array. Most practical use cases entail copying into a differently sized array.
10

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 Comments

Thank you very much!, after one hour searching this is what I was looking for!
How can you modify b if it is a val?
Even though b is val which prevents us from reassigning it to some other value, Array is mutable.
7

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.

Comments

3

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.