我试图了解从 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)
}
这意味着它只是将新数组的内容复制到同一数组而不调整其大小。相比之下,JDK
中的 ArrayList
只要我们从中删除元素,就会调整数组的大小。
我的理解哪里错了?
最佳答案
我认为reduceToSize
方法减少了数组的大小。
def reduceToSize(sz: Int) {
require(sz <= size0)
while (size0 > sz) {
size0 -= 1
array(size0) = null
}
}
关于java - 了解 Scala 中的 ArrayBuffer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45411993/