Java 理解Scala中的ArrayBuffer

Java 理解Scala中的ArrayBuffer,java,scala,Java,Scala,我试图了解从ArrayBuffer中删除元素的工作原理。这是: 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

我试图了解从
ArrayBuffer
中删除元素的工作原理。这是:

  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)
  }
这意味着它只是将新数组的内容复制到同一个数组中,而不调整其大小。相反,
JDK
中的
ArrayList
只要我们从数组中删除元素,它就会调整数组的大小


我的理解哪里错了?

我认为
reduceToSize
方法减少了数组的大小

  def reduceToSize(sz: Int) {
    require(sz <= size0)
    while (size0 > sz) {
      size0 -= 1
      array(size0) = null
    }
  }
def reduceToSize(sz:Int){
要求(深圳){
尺寸0-=1
数组(size0)=空
}
}

我认为
reduceToSize
方法可以减小数组的大小

  def reduceToSize(sz: Int) {
    require(sz <= size0)
    while (size0 > sz) {
      size0 -= 1
      array(size0) = null
    }
  }
def reduceToSize(sz:Int){
要求(深圳){
尺寸0-=1
数组(size0)=空
}
}

对于Java
数组列表
它也不会收缩数据数组,只需为删除的元素设置
空值
Scala
ArrayBuffer
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;
}

对于Java
ArrayList
它也不会收缩数据数组,只需为删除的元素设置
null
Scala
ArrayBuffer
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;
}

不太清楚。如果我们将null设置为使用新大小重新创建数组,是否完全相同?@St.Antario重新创建数组的成本要高得多,因此只需将元素设置为null,并使GC能够完成其工作就更合适了。我们并不真正关心内部数组的实际大小,但是private field
size0
的值不是很清楚。如果我们将null设置为使用新大小重新创建数组,是否完全相同?@St.Antario重新创建数组的成本要高得多,因此只需将元素设置为null,并使GC能够完成其工作就更合适了。我们并不关心内部数组的实际大小,而是关心private field
size0
的值。这意味着我们实际上有一个大小相同的数组,但元素设置为null,对吗?是的,也许这篇文章对你有帮助:这意味着我们实际上有一个大小相同的数组,但元素设置为null,对吗?是的,也许这篇文章对你有帮助: