What is the difference between ArrayBuffer and Array

前端 未结 4 1608
悲&欢浪女
悲&欢浪女 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:44

    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.

    0 讨论(0)
  • 2020-12-14 18:48

    Another difference is in term of reference and value equality

    Array(1,2) == Array(1,2)              // res0: Boolean = false
    ArrayBuffer(1, 2) == ArrayBuffer(1,2) // res1: Boolean = true
    

    The reason for the difference is == routes to .equals where Array.equals is implemented using Java's == which compares references

    public boolean equals(Object obj) {
      return (this == obj);
    }
    

    whilst ArrayBuffer.equals compares elements contained by ArrayBuffer using sameElements method

      override def equals(o: scala.Any): Boolean = this.eq(o.asInstanceOf[AnyRef]) || (
        o match {
          case it: Seq[A] => (it eq this) || (it canEqual this) && sameElements(it)
          case _ => false
        }
      )
    

    Similarly, contains behaves differently

    Array(Array(1,2)).contains(Array(1,2))                   // res0: Boolean = false
    ArrayBuffer(ArrayBuffer(1,2)).contains(ArrayBuffer(1,2)) // res1: Boolean = true
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-14 19:00

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

    0 讨论(0)
提交回复
热议问题