clone
不仅使浅拷贝,你需要深拷贝:
scala> import collection.mutable.ListBuffer
import collection.mutable.ListBuffer
scala> var a = ListBuffer(ListBuffer(1, 2), ListBuffer(3,4))
a: scala.collection.mutable.ListBuffer[scala.collection.mutable.ListBuffer[Int]] = ListBuffer(ListBuffer(1, 2), ListBuffer(3, 4))
scala> var b = a.clone
b: scala.collection.mutable.ListBuffer[scala.collection.mutable.ListBuffer[Int]] = ListBuffer(ListBuffer(1, 2), ListBuffer(3, 4))
scala> b(0)(0) = 100
scala> a
res1: scala.collection.mutable.ListBuffer[scala.collection.mutable.ListBuffer[Int]] = ListBuffer(ListBuffer(100, 2), ListBuffer(3, 4))
scala> b
res2: scala.collection.mutable.ListBuffer[scala.collection.mutable.ListBuffer[Int]] = ListBuffer(ListBuffer(100, 2), ListBuffer(3, 4))
scala> var c = a.clone.map(_.clone)
c: scala.collection.mutable.ListBuffer[scala.collection.mutable.ListBuffer[Int]] = ListBuffer(ListBuffer(100, 2), ListBuffer(3, 4))
scala> c(0)(0) = 1000
scala> c
res3: scala.collection.mutable.ListBuffer[scala.collection.mutable.ListBuffer[Int]] = ListBuffer(ListBuffer(1000, 2), ListBuffer(3, 4))
scala> a
res4: scala.collection.mutable.ListBuffer[scala.collection.mutable.ListBuffer[Int]] = ListBuffer(ListBuffer(100, 2), ListBuffer(3, 4))
为了实现深拷贝,是'变种C = a.clone.map(_克隆。)'理想的方式是什么? –
对于这样简单的事情,我会说是的,对于更复杂或更深层的东西,你可能需要一个更好的解决方案(如[this](https://github.com/kostaskougios/cloning)?)。 –