通过反向的ArrayList迭代给IndexOutOfBoundsException异常 [英] Reverse iteration through ArrayList gives IndexOutOfBoundsException

查看:248
本文介绍了通过反向的ArrayList迭代给IndexOutOfBoundsException异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我反向遍历一个ArrayList我得到一个IndexOutOfBoundsException异常。我试图做向前迭代并没有问题。我希望,知道有列表中的五行。在code是如下:

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异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆