0

I'm trying to undersatend how removing elements from ArrayBuffer works. Here is it:

  override def remove(n: Int, count: Int) {
    if (count < 0) throw new IllegalArgumentException("removing negative number of elements: " + count.toString)
    else if (count == 0) return  // Did nothing
    if (n < 0 || n > size0 - count) throw new IndexOutOfBoundsException("at " + n.toString + " deleting " + count.toString)
    copy(n + count, n, size0 - (n + count))
    reduceToSize(size0 - count)
  }

The thing is copy is implemented as follows:

protected def copy(m: Int, n: Int, len: Int) {
  scala.compat.Platform.arraycopy(array, m, array, n, len)
}

It means it just copies the content of the new array to the same array without resizing it. In contrast, ArrayList in JDK resizes array as long as we delete elements from it.

Where is my understanding wrong?

2 Answers 2

1

The reduceToSize method reduce the size of array I think.

  def reduceToSize(sz: Int) {
    require(sz <= size0)
    while (size0 > sz) {
      size0 -= 1
      array(size0) = null
    }
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Not quite clear. Is it exactly the same if we set null as recreating array with a new size?
@St.Antario Recreating array is much more expensive, so just set the element to null and make GC can do its work is more appropriate. We don't really care about the real size of the inner array, but the value of private field size0.
1

For the Java ArrayList it also not shrink the data array, just set the null for the removed elements for GC them. Scala ArrayBuffer has done nearly same thing with ArrayList

public E remove(int index) {
    rangeCheck(index);

    modCount++;
    E oldValue = elementData(index);

    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);
    elementData[--size] = null; // clear to let GC do its work

    return oldValue;
}

2 Comments

So it means we actually have an array of the same size, but with the elements set to null, right?
Yes, maybe this post is helpful for you: stackoverflow.com/questions/41933700/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.