Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse iteration through ArrayList gives 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 

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.

like image 289
Ankur Avatar asked Feb 24 '09 02:02

Ankur


People also ask

How do you reverse iterate in Java?

Apache Common provides ReverseListIterator that we can use to iterate list in reverse order. The first call to next() will return the last element from the list, the next call to next() will return the previous element, and so on. hasNext() method checks if there is another element.

Can ArrayList be iterated?

An Iterator can be used to loop through an ArrayList. The method hasNext( ) returns true if there are more elements in ArrayList and false otherwise. The method next( ) returns the next element in the ArrayList and throws the exception NoSuchElementException if there is no next element.

Can iterator go backwards?

C++ Iterators Reverse Iterators A reverse iterator is made from a bidirectional, or random access iterator which it keeps as a member which can be accessed through base() . To iterate backwards use rbegin() and rend() as the iterators for the end of the collection, and the start of the collection respectively.


1 Answers

Avoid indexes altogether? How about:

for (ListIterator iterator = list.listIterator(list.size()); iterator.hasPrevious();) {   final Object listElement = iterator.previous(); } 
like image 152
Sualeh Fatehi Avatar answered Sep 28 '22 09:09

Sualeh Fatehi