How do I do a deep copy of a 2D array in Scala?
For example
val a = Array[Array[Int]](2,3)
a(1,0) = 12
I want val b to copy value开发者_开发问答s of a but without pointing to the same array.
You can use the clone
method of the Array
class. For a multi-dimensional Array
, use map
on the extra dimensions. For your example, you get
val b = a.map(_.clone)
Just transpose it twice
a.transpose.transpose
Given:
val a = Array[Array[Int]]
you could try:
for(inner <- a) yield {
for (elem <- inner) yield {
elem
}
}
A deeper question is WHY you would want do do so with ints? The whole point of using immutable types is to avoid exactly this kind of construct.
If you have a more generic Array[Array[T]]
, then your main concern is how to clone the instance of T
, not how to deep-clone the array.
精彩评论