What is the difference between ArrayBuffer and Array

Use an Array if the length of Array is fixed, and an ArrayBuffer if the length can vary.


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


Both Array and ArrayBuffer are mutable, which means that you can modify elements at particular indexes: a(i) = e

ArrayBuffer is resizable, Array isn't. If you append an element to an ArrayBuffer, it gets larger. If you try to append an element to an Array, you get a new array. Therefore to use Arrays efficiently, you must know its size beforehand.

Arrays are implemented on JVM level and are the only non-erased generic type. This means that they are the most efficient way to store sequences of objects – no extra memory overhead, and some operations are implemented as single JVM opcodes.

ArrayBuffer is implemented by having an Array internally, and allocating a new one if needed. Appending is usually fast, unless it hits a limit and resizes the array – but it does it in such a way, that the overall effect is negligible, so don't worry. Prepending is implemented as moving all elements to the right and setting the new one as the 0th element and it's therefore slow. Appending n elements in a loop is efficient (O(n)), prepending them is not (O(n²)).

Arrays are specialized for built-in value types (except Unit), so Array[Int] is going to be much more optimal than ArrayBuffer[Int] – the values won't have to be boxed, therefore using less memory and less indirection. Note that the specialization, as always, works only if the type is monomorphic – Array[T] will be always boxed.

Tags:

Arrays

Scala