我是新來的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]()
如何更新地圖添加新元素放入列表緩衝區。
我是新來的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]()
如何更新地圖添加新元素放入列表緩衝區。
你應當認真考慮在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))))
它現在工作!非常感謝 –
單獨創建一個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))
,你可以嘗試做 –
已經嘗試過,但沒有機會。我想要的只是一個指導!與我有什麼我不得不說cuz我很困惑 –
所以告訴我們你有什麼嘗試 –