David
David

Reputation: 103

what's the difference between Array and Buffer when using scala?

when I work on some task using scala , I wrote some code as follows:

object He {
  def main(args: Array[String]): Unit = {
    var myMatrix = Array.ofDim[String](3,3)
    // build a matrix
    for (i <- 0 to 1) {
      for ( j <- 0 to 1) {
        myMatrix(i)(j) = "faf";
      }
    }
    var eventbuffer = for(i <- myMatrix) yield for(j <- i) yield j
    var eventArray =  for(i <- eventbuffer) yield i.toArray
    var eventpool:Array[(String, Array[String])] =   eventArray.toArray.map(son => (son(0), son))
  }
}

I want to ask the question ,what's the differece between the eventbuffer and eventArray?Last,what will the eventpool be like? I am really confused,Thank for helping me for that

Upvotes: 5

Views: 657

Answers (1)

Luka Jacobowitz
Luka Jacobowitz

Reputation: 23502

In Scala an Array is just a JVM Array, while the various Buffers are actual classes.

An Array[String] ist the same as a String[] in Java. You can think of an ArrayBuffer as an ArrayList in Java (they're very similar, but not equivalent) and of the ListBuffer as a Java LinkedList (again, similar, but not the same).

One should note however, that in your example eventbuffer is not a Buffer, but an Array of Arrays. In fact it is pretty much an exact copy of myMatrix, so the call to the toArray method is actually redundant.

Upvotes: 8

Related Questions