Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ArrayBuffer works in memory?

I want to use ArrayBuffer in my program to keep list of numbers. I want to use it as queue. Each time delete the first item in the list and use it. Then I was wondering each time that I am deleting the first item do all other numbers in the queue shift one place. I mean next time can I again read item(0) ?

like image 280
Rubbic Avatar asked Feb 11 '23 22:02

Rubbic


1 Answers

If you look into the Scala source code or ArrayBuffer, you'll see the following implementation of remove:

/** Removes the element on a given index position. It takes time linear in
   *  the buffer size.
   *
   *  @param n       the index which refers to the first element to delete.
   *  @param count   the number of elements to delete
   *  @throws Predef.IndexOutOfBoundsException if `n` is out of bounds.
   */
  override def remove(n: Int, count: Int) {
    require(count >= 0, "removing negative number of elements")
    if (n < 0 || n > size0 - count) throw new IndexOutOfBoundsException(n.toString)
    copy(n + count, n, size0 - (n + count))
    reduceToSize(size0 - count)
  }

So the removed element will no longer be present in the array, but indeed, the removal means copying all elements ("shifting" in your definition), and it will be slow for longer arrays.

like image 74
Ashalynd Avatar answered Feb 15 '23 09:02

Ashalynd