你也可以使用clone 方法!!
def copy(bild: Array[Array[Int]]): Unit = {
val copy = bild.clone
}
更新:
由于 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))
这里对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))
因此..将问题中的复制方法重构为..
def copy(bild: Array[Array[Int]]): Unit = {
val copy = bild.map(_.clone)
}