复制二维数组

4 arrays for-loop scala

我想复制一个二维数组.我想用for循环做这个,我知道怎么做,但我无法完成剩下的工作.

def copy(bild:Array[Array[Int]]):Unit = {

    for(x <- 0 until bild.length)
    for(y <- 0 until bild(x).length) {
        bild(x)(y) = 
        //i don't know how to create the new array
    }

}
Run Code Online (Sandbox Code Playgroud)

Shr*_*rey 7

你也可以使用clone方法!!

def copy(bild: Array[Array[Int]]): Unit = {
    val copy = bild.clone
} 
Run Code Online (Sandbox Code Playgroud)

更新:

因为,Array [Int]仍然是可变引用,克隆仍然无法解决问题..正如Andriy Plokhotnyuk在评论中提到的那样.

问题:

val og = Array(Array(1, 2, 3), Array(4,5,6))      //> og  : Array[Array[Int]] = Array(Array(1, 2, 3), Array(4, 5, 6))
val copy = og.clone                               //> copy  : Array[Array[Int]] = Array(Array(1, 2, 3), Array(4, 5, 6))
copy(0)(0) = 7
og                                                //> res2: Array[Array[Int]] = Array(Array(7, 2, 3), Array(4, 5, 6))
copy                                              //> res3: Array[Array[Int]] = Array(Array(7, 2, 3), Array(4, 5, 6))
Run Code Online (Sandbox Code Playgroud)

这里任何更新copy都会反映到og..

索尔:

所以我主要需要克隆Array [Int] ..因此..

val og = Array(Array(1, 2, 3), Array(4,5,6))      //> og  : Array[Array[Int]] = Array(Array(1, 2, 3), Array(4, 5, 6))
val copy = og.map(_.clone)                        //> copy  : Array[Array[Int]] = Array(Array(1, 2, 3), Array(4, 5, 6))
copy(0)(0) = 7
og                                                //> res2: Array[Array[Int]] = Array(Array(1, 2, 3), Array(4, 5, 6))
copy                                              //> res3: Array[Array[Int]] = Array(Array(7, 2, 3), Array(4, 5, 6))
Run Code Online (Sandbox Code Playgroud)

因此..重构问题中的复制方法到..

def copy(bild: Array[Array[Int]]): Unit = {
    val copy = bild.map(_.clone) 
}
Run Code Online (Sandbox Code Playgroud)