I have code like below
val g = new Graph(vertices)
//Firts part
(1 to vertices).par.foreach( i => g + new Vertex(i))
//Second part
for (i <- 1 to edges) {
val data = scala.io.StdIn.readLine()
val d = data.split(" ")
val v1 = d(0).toInt
val v2 = d(1).toInt
val length = d(2).toInt
g+(v1, v2, length)
}
I want to execute first and second part of code sequentially. At present for loop run before the all Vertex have added to g. In code + (plus) define add new instance of Vertex to MutableList.
I'am new in scala, please help
I find out the solution. I read more about add new elements to collection parallel and it isn't thread save. I replaced MutableList to fixedsize array, and I add new element by index.
Some code below:
class Graph(val end: Int) {
private val vertices : Array[Vertex] = new Array[Vertex](end)
def +(index: Int, v: Vertex): Unit = {
vertices(index) = v
}
(...)
}
//Firts part
(1 to vertices).par.foreach( i => g + (i-1,new Vertex(i))) //add new vertex to array by index