scala 如何在Scala中有效地将数组复制到另一个数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32431729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to efficient copy an Array to another in Scala?
提问by BranY
How I can use another way to copy a Arrayto another Array?
我如何使用另一种方式将 a 复制Array到另一个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:
第二种方法是使用for loop,例如:
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)
回答by Ionut
You can use .clone
您可以使用 .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)
回答by tuxdna
The shortest and an idiomatic way would be to use mapwith identitylike this:
最短和习惯的方法是使用map具有identity这样的:
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.
此副本适用于所有集合类型,而不仅仅是Array.
回答by elm
Consider Array.copyin this example where destis a mutable Array,
考虑Array.copy在这个例子中 wheredest是一个 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 APInote Scala Array.copyis equivalent to Java System.arraycopy, with support for polymorphic arrays.
从Scala Array API注释 ScalaArray.copy等同于 Java System.arraycopy,支持多态数组。
回答by Patrick Pisciuneri
Another option is to create the new array, B, using Aas a variable argument sequence:
另一种选择是创建新数组, B,A用作变量参数序列:
val B = Array(A: _*)
The important thing to note is that using the equal operator, C = A, results in Cpointing to the original array, A. That means changing Cwill change A:
需要注意的重要一点是,使用等号运算符C = A, 会导致C指向原始数组A。这意味着改变C会改变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)

