2017-07-31 21 views
0

我試圖忽略從ArrayBuffer中刪除元素是如何工作的。下面是它:瞭解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 < 0 || n > size0 - count) throw new IndexOutOfBoundsException("at " + n.toString + " deleting " + count.toString) 
    copy(n + count, n, size0 - (n + count)) 
    reduceToSize(size0 - count) 
    } 

的事情是如下副本實現:

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

這意味着它只是複製新陣列的同一個數組內容而不調整其大小。相比之下,ArrayListJDK中調整了數組的大小,只要我們從中刪除元素即可。

我的理解錯在哪裏?

回答

1

reduceToSize方法減少了我認爲數組的大小。

def reduceToSize(sz: Int) { 
    require(sz <= size0) 
    while (size0 > sz) { 
     size0 -= 1 
     array(size0) = null 
    } 
    } 
+0

不太清楚。如果我們將null設置爲用新大小重新創建數組,它是否完全相同? –

+0

@ St.Antario重新創建陣列要貴得多,因此只需將元素設置爲null,並使GC可以完成其工作就更合適。我們並不關心內部數組的實際大小,而是私有字段'size0'的值。 – aristotll

1

對於的JavaArrayList也沒有收縮數據陣列,只需設置null去除元素GC他們。 斯卡拉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; 
} 
+0

所以這意味着我們實際上有一個相同大小的數組,但是將元素設置爲null,對吧? –

+0

是的,也許這個帖子對你很有幫助:https://stackoverflow.com/questions/41933700/why-java-arraylists-do-not-shrink-automatically – chengpohi