Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 779
David Avatar asked Mar 03 '17 08:03

David


1 Answers

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.

like image 192
Luka Jacobowitz Avatar answered Oct 14 '22 12:10

Luka Jacobowitz