简体   繁体   中英

Index out of bounds on ArrayList sublist

I have an ArrayList of 11,000 objects that I want to process 200 at a time using ArrayList.subList(). When I put it in a for loop, I get index out of bounds. How do I best control the offset?

for(int i = 0; i< aList.size(); i+=200){
   process(aList(i,i+200));
}

You can get the minimum of List.size() and the counter i + 200 :

for (int i = 0; i < aList.size(); i += 200) {
    int min = Math.min(aList.size(), i + 200);
    process(aList.subList(i, min));
}

For the case of 11000 objects, the last iteration will get the sublist from 10800 until 10999.

This will also take into consideration the case where the list size is not exactly a multiple of 200.

Assuming your ArrayList size is exactly 11000:

for(int i = 200; i< aList.size(); i+=200){
   process(aList(i-200,i-1));  //0 to 199, 200 - 399......  (0 - 10999 = 11000)
}

The reason you are getting an out of bounds error on the index is that i to i+200 is actually processing 201 items. For instance 0 to 200 is 201 items. Change your process(aList(i,i+200)); to process(aList(i,i+199)); The reason this caused an error is that the last loop is referencing 1 item past the last item. It is referencing index 11,001.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM