views:

3100

answers:

4

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.

+8  A: 

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
}

Note that your forward iteration works because it stops before reaching list.size().

David Zaslavsky
You're halfway there - he has to end at j>= 0;
Paul Tomblin
Yep thanks, everyone, just came back to say what a silly question it was. And already had several answers. Thanks.
Ankur
@Paul: thanks, typo on my part. I edited in the fix.
David Zaslavsky
+2  A: 

Java arrays are zero-indexed. You will have to set j = list.size() - 1 and continue until j = 0.

Coxy
+5  A: 

The list.size() is past the last allowable index.

try

for(int j=list.size() -1;j>=0;j--){
  System.out.println(list.get(j));
}
Clint
Actually no, list.size() is not an allowable index - it's one beyond that - which is why you are using size() -1 in your example :)
matt b
+3  A: 

Avoid indexes altogether? How about:

for (ListIterator iterator = list.listIterator(list.size()); iterator.hasPrevious();) {
  final Object listElement = iterator.previous();
}
Sualeh Fatehi
Well, it's more verbose than the indexed version.
Seun Osewa