Graph representation (adjacency list) using HashMap [Int, Vector [Int]] (Scala)?

I was wondering how (if possible) I can make the adjacency list view of a (mutable) graph through HashMap[Int, Vector[Int]]. HashMapwill change of course.

I am currently set up as HashMap[Int, ArrayBuffer[Int]], but the fact that I can change every cell in the ArrayBuffer makes me uncomfortable, although I'm sure I don't. I would use it ListBuffer[Int], but I would like to get quick random access to my neighbors because of my need to do quick random walks on graphs. A Vector[Int]will solve this problem, but do it anyway?

As far as I know (tried this in REPL), this will not work:

scala> val x = new mutable.HashMap[Int, Vector[Int]]
x: scala.collection.mutable.HashMap[Int,Vector[Int]] = Map()

scala> x(3) = Vector(1)

scala> x(3) += 4 // DOES NOT WORK

I need to be able to simultaneously add it at any time, as well as arbitrarily access any element inside it (subject to the index). Is it possible?

Thank! -kstruct

+3
source share
1 answer

Using Vector:

x += 3 -> (x(3) :+ 4)  //x.type = Map(3 -> Vector(1, 4))

You may notice that this will fail if there is no existing key, so you can configure your card as

val x = new mutable.HashMap[Int, Vector[Int]] withDefaultValue Vector.empty
+5
source

All Articles