gpt4 book ai didi

scala - Scala追加到可变的LinkedList

转载 作者:行者123 更新时间:2023-12-03 14:44:39 26 4
gpt4 key购买 nike

请检查一下

import scala.collection.mutable.LinkedList

var l = new LinkedList[String]

l append LinkedList("abc", "asd")

println(l)
// prints
// LinkedList()




import scala.collection.mutable.LinkedList

var l = new LinkedList[String]

l = LinkedList("x")
l append LinkedList("abc", "asd")

println(l)
// prints
// LinkedList(x, abc, asd)


为什么第二个代码段有效但第一个无效?这是在Scala 2.10上

最佳答案

该文档说If this is empty then it does nothing and returns that. Otherwise, appends that to this.。就是您所观察到的。如果您确实需要可变列表,建议您改用scala.collection.mutable.ListBuffer,它可以

val lb = new ListBuffer[Int]

scala> lb += 1
res14: lb.type = ListBuffer(1)

scala> lb
res15: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1)

scala> lb ++= Seq(1,2,3)
res17: lb.type = ListBuffer(1, 1, 2, 3, 1, 2, 3)

scala> lb
res18: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 1, 2, 3, 1, 2, 3)

关于scala - Scala追加到可变的LinkedList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15761608/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com