ObservableBuffer 在 Scala 中给出 IndexOutOfBounds

ObservableBuffer giving IndexOutOfBounds in Scala

我被迷住了。下面的代码给我一个 indexoutofbound 错误。但是,如果我要删除启用 for(j <- i until tmpArray.length) 的斜杠,它就会起作用。我真的不明白为什么会这样,希望得到解释。

 for(i <- 0 until tmpArray.length)
{
 // for(j <- i until tmpArray.length)
 // {
    if( date.getValue != null && tmpArray(i).date != date.getValue )
    {
      tmpArray.remove(i)
    }
//  }
}

您在 "iterate" 上修改数组。

您实际上是在 0 until tmpArray.length 范围内迭代,这是预先计算好的。在某些时候,您减少了数组的长度(或者,我假设是这样,因为我在 Array class 上找不到 remove)。但它仍将继续迭代,直到您创建范围时的最后一个索引。

当您取消注释内部 for 块时,您将使其重新计算外部 for 的每个步骤的范围。如果 i >= tmpArray.lengthj 范围内就什么也没有了。所以它无意中防止了这种失败。

这是非常 C 风格(命令式)的代码。看起来您要做的只是从数组中删除一些项目。这就是 filter 的目的。

val result = tmpArray.filter { d =>
  if(date.getValue != null && d != date.getValue) false else true
}

这通过将匿名函数传递给 tmpArray.filter 创建了一个 new 数组 (result)。它会将数组中的每个项目传递给您的 "predicate",如果它 returns true,它将将该项目保留在 result 中,否则它将忽略它。

你应该注意到我避免说 "loop"。 Scala 的 for 不是用来制作循环的。它实际上是调用 foreachmap 等方法的语法糖。 Google "scala for comprehensions" 了解更多详情。

如果你坚持使用索引和循环变量创建 C 风格的循环,你会想要使用 while,这样你就可以每次检查是否 i < tmpArray.length