简体   繁体   English

ArrayList子列表上的索引超出范围

[英]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(). 我有一个11,000个对象的ArrayList,我想使用ArrayList.subList()一次处理200个对象。 When I put it in a for loop, I get index out of bounds. 当我将它放在for循环中时,索引超出范围。 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 : 您可以获得List.size()和计数器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. 对于11000个对象,最后一次迭代将获得从10800到10999的子列表。

This will also take into consideration the case where the list size is not exactly a multiple of 200. 这还将考虑列表大小不完全是200的倍数的情况。

Assuming your ArrayList size is exactly 11000: 假设您的ArrayList大小恰好是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. 您在索引上出现超出范围错误的原因是i到i + 200实际上正在处理201个项目。 For instance 0 to 200 is 201 items. 例如0到200是201个项目。 Change your process(aList(i,i+200)); 更改您的process(aList(i,i+200)); to process(aList(i,i+199)); 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. 它引用索引11,001。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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