java - 了解 Scala 中的 ArrayBuffer

标签 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 < 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/

相关文章:

Java 泛型类型推断困惑

scala - 我什么时候应该在scala中使用 "new"?

scala - 光滑表定义中的自定义映射列类型

scala - 如何将 Option 与 Spark UDF 结合使用

java - getResourceAsStream() 适用于 Windows,但不适用于 Linux

java - 关于动态规划我需要了解什么?

java - 如何增加新文件名中的数字?

java - MVC模式中为什么Controller要调用View?

scala - scala 对象构造函数可以作为竞争条件运行两次吗?

scala - 是否有将 Future[Reader[A, X]] 转换为 Reader[A, Future[X]] 的通用方法?