我有var x
类型ListBuffer[ListBuffer[Int]]
我使用函数clone
进行克隆并设置为另一个var y
,然后使用函数{{1}在这个新的update
上更新内容,但是当我检查var y
的原始内容时,它与var x
相同?为什么是这样?我究竟做错了什么?他们的解决方法是什么?我试图获得ListBuffer的副本,我可以修改,而无需更改初始ListBuffer的原始内容。
答案 0 :(得分:5)
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))