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
The error:
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.
Start the iteration at
list.size() - 1because array (orArrayList) elements are numbered from 0 up through 1 less than the size of the list. This is a fairly standard idiom:Note that your forward iteration works because it stops before reaching
list.size().