Home > Back-end >  Scala ArrayBuffer append always at end or not?
Scala ArrayBuffer append always at end or not?

Time:08-06

With the following code repeated many times:

var name = ArrayBuffer[String]() 
name  = "GeeksForGeeks"
...
name -= "GeeksForGeeks"
...
name  = "xyz"

Can I always guarantee that an entry is added at the end even if the max size of ArrayBuffer is reached and a new array allocated, even if there are are empty slots in ArrayBuffer due to deletion of element(s)? Or is the array compacted upon a deletion of an entry always? I cannot see from examples done.

Not 100% clear from docs. I want to be really sure.

CodePudding user response:

= is an alias for addOne, and despite not being clearly documented as such addOne is also the implementation of append for all Buffers. So in other words = and append are the same thing for an ArrayBuffer. And append by definition always adds elements at the end.

The exception is if you were to mutate an ArrayBuffer concurrently from multiple threads. Then you will probably corrupt the internal data structures.

  • Related