克隆ListBuffer不可变问题Scala

时间:2016-11-15 05:47:48

标签: scala list copy immutability mutable

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

1 个答案:

答案 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))