Reverse iteration through ArrayList gives IndexOutOfBoundsException(通过 ArrayList 的反向迭代给出 IndexOutOfBoundsException)
问题描述
当我对 ArrayList 进行反向迭代时,我得到了 IndexOutOfBoundsException.我尝试进行前向迭代,没有问题.我期望并且知道列表中有五个元素.代码如下:
When I reverse iterate over an ArrayList I am getting a IndexOutOfBoundsException. I tried doing forward iteration and there is no problem. I expect and know that there are five elements in the list. The code is below:
Collection rtns = absRtnMap.values();
List list = new ArrayList(rtns);
Collections.sort(list);
for(int j=list.size();j>0;j=j-1){
  System.out.println(list.get(j));
}
<小时>
前向迭代 - 工作正常,但对我没用:
Forward iteration - which is working fine, but not useful for me:
for(int j=0;j<list.size();j++){
    System.out.println(list.isEmpty());
    System.out.println(list.get(j));
} // this worked fine
<小时>
错误:
Exception in thread "Timer-0" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
    at java.util.ArrayList.RangeCheck(Unknown Source)
    at java.util.ArrayList.get(Unknown Source)
    at model.Return.getReturnMap(Return.java:61)
    at controller.Poller$1.run(Poller.java:29)
    at java.util.TimerThread.mainLoop(Unknown Source)
    at java.util.TimerThread.run(Unknown Source)
另外,如果有人知道反向迭代的更好用语,我很乐意尝试一下.
Also if anyone knows of a better idiom for reverse iteration I would be happy to try that out.
推荐答案
从 list.size() - 1 开始迭代,因为数组(或 ArrayList)元素是从 0 到小于列表大小的 1 编号.这是一个相当标准的成语:
Start the iteration at list.size() - 1 because array (or ArrayList) elements are numbered from 0 up through 1 less than the size of the list. This is a fairly standard idiom:
for (int j = list.size() - 1; j >= 0; j--) {
    // whatever
}
请注意,您的前向迭代是有效的,因为它会在  到达 list.size() 之前停止.
Note that your forward iteration works because it stops before reaching list.size().
这篇关于通过 ArrayList 的反向迭代给出 IndexOutOfBoundsException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过 ArrayList 的反向迭代给出 IndexOutOfBoundsException
				
        
 
            
        - Eclipse 的最佳 XML 编辑器 2022-01-01
 - GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
 - 转换 ldap 日期 2022-01-01
 - 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
 - java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
 - 未找到/usr/local/lib 中的库 2022-01-01
 - 如何指定 CORS 的响应标头? 2022-01-01
 - 获取数字的最后一位 2022-01-01
 - 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
 - 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
 
						
						
						
						
						
				
				
				
				