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
The list.size() is past the last allowable index.
for(int j = list.size() - 1; j >= 0; j--) {
System.out.println(list.get(j));
}
If the lists are fairly small so that performance is not a real issue, one can use the reverse
-metod of the Lists
-class in Google Guava
. Yields pretty for-each
-code, and the original list stays the same. Also, the reversed list is backed by the original list, so any change to the original list will be reflected in the reversed one.
import com.google.common.collect.Lists;
[...]
final List<String> myList = Lists.newArrayList("one", "two", "three");
final List<String> myReverseList = Lists.reverse(myList);
System.out.println(myList);
System.out.println(myReverseList);
myList.add("four");
System.out.println(myList);
System.out.println(myReverseList);
Yields the following result:
[one, two, three]
[three, two, one]
[one, two, three, four]
[four, three, two, one]
Which means that reverse iteration of myList can be written as:
for (final String someString : Lists.reverse(myList) {
//do something
}
You can do this if you are comfortable with foreach loop.
List<String> list = new ArrayList<String>();
list.add("ABC");
list.add("DEF");
list.add("GHI");
ListIterator<String> listIterator = list.listIterator(list.size());
while(listIterator.hasPrevious()){
System.out.println(listIterator.previous());
}