【问题标题】:indexoutofboundsexception in Mongodb javaMongodb java中的indexoutofboundsexception
【发布时间】:2017-03-22 11:11:20
【问题描述】:
for(int i=0; i<= field.length; i++){
    String[] field = allFields.split(",");
    String field1 = "$"+field[i];
    BsonField includeFields = Accumulators.first(field[i], field1);
    includeList.add(includeFields);
}
    group = Aggregates.group(groupByField,includeList);

allFields 将包含我要选择的列(“ID,NAME”)。

为什么它给我 indexoutofboundsexception ?

【问题讨论】:

  • 确保字段[i]中的i值不超过字段长度
  • 当我打印 includeFields name='ID', value=Expression{name='$first', expression=$ID} 。是不是因为这个@radhakrishnan
  • i 定义在哪里?
  • 我通过在循环中删除 = for(int i=0; i&lt;= field.length; i++){@Veeram 解决了这个问题

标签: java mongodb aggregation-framework


【解决方案1】:

仅供未来访问者参考 假设我们有一个名为 foo 的数组,其中包含 10 个项目。 如果我们尝试使用以下代码进行迭代会发生什么?:

for(int i = 0;i<=foo.length;i++){
   //some code that uses foo[i] here
}

答案是IndexOutOfBoundsException 原因很简单。如前所述foo包含10个元素 这意味着您可以使用foo[0] to foo[9] 访问它们 由于数组索引从 0 开始 foo[9] 包含数组中的最后一个元素(第 10 个元素)`

for 循环中发生了什么?

在您进行迭代时,您始终检查i&lt;=foo.length 以继续。 问题是当i 的值为9 时,表达式i&lt;=foo.length(which means i&lt;=10) 的计算结果为true。这意味着for 循环将运行最后一次。当这种情况发生在您的循环中时,您将尝试访问foo[10] 不存在,因此 IndexOutOfBoundsException

所以请记住,当您想要遍历数组时,总是使用i&lt;foo.length

所以你也想通了解决你的问题是这样的:

for(int i=0; i< field.length; i++){
    String[] field = allFields.split(",");
    String field1 = "$"+field[i];
    BsonField includeFields = Accumulators.first(field[i], field1);
    includeList.add(includeFields);
}

【讨论】:

    猜你喜欢
    • 2018-12-03
    • 2013-09-30
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 2016-03-22
    • 2019-10-05
    • 1970-01-01
    • 2019-08-11
    相关资源
    最近更新 更多