开发者

Deep copy of 2D array in Scala?

开发者 https://www.devze.com 2022-12-13 09:57 出处:网络
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 c

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消