What is the difference between ArrayBuffer and Array

前端 未结 4 1782
悲&欢浪女
悲&欢浪女 2020-12-14 18:16

I\'m new to scala/java and I have troubles getting the difference between those two.

By reading the scala doc I understood that ArrayBuffer are made to

4条回答
  •  庸人自扰
    2020-12-14 18:57

    The one other difference is, Array's element created as on when its declared but Array Buffer's elements not created unless you assign values for the first time.

    For example. You can write Array1(0)="Stackoverflow" but not ArrayBuffer1(0)="Stackoverflow" for the first time value assignments.

    (Array1 = Array variable & ArrayBuffer1 = ArrayBuffer variable)

    Because as we know, Array buffers are re-sizable, so elements created when you insert values at the first time and then you can modify/reassign them at the particular element.

    Array:

    Declaring and assigning values to Int Array.

    val favNums= new Array[Int](20)
    
    for(i<-0 to 19){
    favNums(i)=i*2
    }
    favNums.foreach(println)
    

    ArrayBuffer:

    Declaring and assigning values to Int ArrayBuffer.

    val favNumsArrayBuffer= new ArrayBuffer[Int]
        for(j<-0 to 19){
        favNumsArrayBuffer.insert(j, (j*2))
        //favNumsArrayBuffer++=Array(j*3)
          }
        favNumsArrayBuffer.foreach(println)
    

    If you include favNumsArrayBuffer(j)=j*2 at the first line in the for loop, It doesn't work. But it works fine if you declare it in 2nd or 3rd line of the loop. Because values assigned already at the first line now you can modify by element index.

    This simple one-hour video tutorial explains a lot.

    https://youtu.be/DzFt0YkZo8M?t=2005

提交回复
热议问题