indexoutofboundsexception in Mongodb java

2019-09-14 17:06发布

问题:

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);

where the allFields will have the columns i want to select("ID,NAME").

why is it giving me indexoutofboundsexception ?

回答1:

Just a reference for future visitors Suppose we have an array called foo which contains 10 items. What happens if we try to iterate using the following code?:

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

The answer is an IndexOutOfBoundsException The reason is simple.As said before foo contains 10 elements which means you can access them using foo[0] to foo[9] Since array indexing starts from 0 foo[9] contains the last element in your array(the 10th element)`

What happens though in the for loop?

As you iterate you always check i<=foo.length to continue. The problem is that when the value of i is 9 the expression i<=foo.length(which means i<=10) evaluates to true.That means that the for loop will run for one last time.When this happens in your loop you will try to access foo[10] which not exists and hence the IndexOutOfBoundsException

So remember that when you want to iterate over an array you always use i<foo.length

So as you too figured it out the solution to your problem is this:

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);
}