2016-08-15 24 views
1

我是新来的Scala和我在一张地图与此结构的listbuffer:添加在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]() 

如何更新地图添加新元素放入列表缓冲区。

+0

,你可以尝试做 –

+0

已经尝试过,但没有机会。我想要的只是一个指导!与我有什么我不得不说cuz我很困惑 –

+1

所以告诉我们你有什么尝试 –

回答

2

你应当认真考虑在Scala中使用case类 - 他们给你很多的好东西是免费的。假设你改变你的类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("[email protected]", 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("[email protected]", 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([email protected],4), Note([email protected],40)))) 
+0

它现在工作!非常感谢 –

1

单独创建一个ListBuffer,并根据需要添加尽可能多的注释。然后,只需创建地图如下:

val lb = scala.collection.mutable.ListBuffer(new Note("[email protected]",1), new Note("[email protected]",2)) 
Map((1,2,3) -> new Person("samar",0,lb))