我有一个MutableList
,我想从中删除一个元素,但我找不到合适的方法。有一种方法可以从ListBuffer
中删除元素:
val x = ListBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9)
x -= 5
我无法在MutableList
上找到等效的方法。
答案 0 :(得分:9)
MutableList
缺少-=
和--=
,因为它没有延伸Shrinkable
特征。可以找到各种动机here。
MutableList
确实有diff
,filter
和其他方法可以帮助您,以防您重新分配变量(或实例化新变量)可能是选项和性能问题并不是最重要的:
var mylist = MutableList(1, 2, 3)
mylist = mylist diff Seq(1)
val myNewList = mylist.filter(_ != 2)
val indexFiltered = mylist.zipWithIndex.collect { case (el, ind) if ind != 1 => el }
您经常可以使用ListBuffer
代替MutableList
,这将解锁所需的-=
和--=
方法:
val mylist = ListBuffer(1, 2, 3)
mylist -= 1 //mylist is now ListBuffer(2, 3)
mylist --= Seq(2, 3) //mylist is now empty
答案 1 :(得分:1)
这不是答案,只是为了警告你有关问题(至少在2.11.x中):
//street magic
scala> val a = mutable.MutableList(1,2,3)
a: scala.collection.mutable.MutableList[Int] = MutableList(1, 2, 3)
scala> a += 4
res7: a.type = MutableList(1, 2, 3, 4)
scala> a
res8: scala.collection.mutable.MutableList[Int] = MutableList(1, 2, 3, 4)
scala> a ++= List(8,9,10)
res9: a.type = MutableList(1, 2, 3, 4, 8, 9, 10)
scala> val b = a.tail
b: scala.collection.mutable.MutableList[Int] = MutableList(2, 3, 4, 8, 9, 10)
scala> b.length
res10: Int = 6
scala> a.length
res11: Int = 7
scala> a ++= List(8,9,10)
res12: a.type = MutableList(1, 2, 3, 4, 8, 9, 10, 8, 9, 10)
scala> b += 7
res13: b.type = MutableList(2, 3, 4, 8, 9, 10, 7)
scala> a
res14: scala.collection.mutable.MutableList[Int] = MutableList(1, 2, 3, 4, 8, 9, 10, 7)
scala> b
res15: scala.collection.mutable.MutableList[Int] = MutableList(2, 3, 4, 8, 9, 10, 7)
scala> a ++= List(8,9,10)
res16: a.type = MutableList(1, 2, 3, 4, 8, 9, 10, 7)
这个例子来自一些要点 - 我已经用#devid_blein #street_magic标签在facebook上发布了它,但在互联网上找不到原始链接。