我是scala的新手,我在这个结构的地图中有一个listbuffer:
class Person(var name: String, var age: Int,note: ListBuffer[Note])
class Note(
email: String,
note: Int)
var m = Map[Tuple3[Int,Int,Int],Person]()
如何更新地图以将新元素添加到listbuffer中。
答案 0 :(得分:2)
你应该强烈考虑在Scala中使用case
类 - 它们免费为你提供了很多好东西。假设您确实将类更改为案例类,以下内容将实现您的目标:
import scala.collection.mutable.ListBuffer
case class Note(email: String, note: Int)
case class Person(var name: String, var age: Int,note: ListBuffer[Note])
val n1 = Note("foo@gmail.com", 4)
val c1 = Person("John", 20, ListBuffer(n1))
val m = scala.collection.mutable.Map[(Int,Int,Int), Person]()
m += ((1,1,1) -> c1)
val n2 = Note("bar@gmail.com", 40)
m += ((1,1,1) -> c1.copy(note = c1.note += n2))
println(m)
res1: scala.collection.mutable.Map[(Int, Int, Int),Person] = Map((1,1,1) -> Person(John,20,ListBuffer(Note(foo@gmail.com,4), Note(bar@gmail.com,40))))
答案 1 :(得分:1)
使用任意数量的笔记单独创建一个ListBuffer。然后只需创建如下地图:
val lb = scala.collection.mutable.ListBuffer(new Note("s@s.com",1), new Note("d@d.com",2))
Map((1,2,3) -> new Person("samar",0,lb))