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
You can reverse by one line that is
Collections.reverse(list);
ArrayList arrayList = new ArrayList();
arrayList.add("A");
arrayList.add("B");
System.out.println("Before Reverse Order : " + arrayList);
Collections.reverse(arrayList);
System.out.println("After Reverse : " + arrayList);
Output
Before Reverse Order : [A, B]
After Reverse : [B, A]
Java arrays are zero-indexed. You will have to set j = list.size() - 1 and continue until j = 0.
The most elegant way is to reverse the array and then use a direct (or even implicit) iterator :
Collections.reverse(arrayList);
for (Object item : arrayList) {
...
}
I know this is an old question, but Java contains a Collections.reverse( List<T> )
method. Why wouldn't you just reverse it and do forward iteration?
Avoid indexes altogether? How about:
for (ListIterator iterator = list.listIterator(list.size()); iterator.hasPrevious();) {
final Object listElement = iterator.previous();
}
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()
.