Incremental Java
Printing an ArrayList Backwards

Printing an ArrayList Backwards

to the smallest. In other words, we're going to print the strings in reverse (backwards) order.

How do we get to the largest index? We know the number of elements in the ArrayList. You can use the size() method for that. The index ranges from 0 to size() - 1 (it's size() - 1, because the indexing begins at 0, instead of 1).

So we need a looping variable that starts at size() - 1 and works all the way down to 0.

Since we know the exact range of indexes we need, we'll use a for loop. Here's how it looks:

for ( int i = list.size() ; i >= 0 ; i-- )
{
}
Now we need to fill in the loop body. Pay attention to the loop variable, i. We use the loop variable to access the String in the ArrayList object from each of the 5 boxes. We use the get() method, which retrieves the String objects.

Go look at the previous lesson, where we have the API for ArrayList and look up the get() method. You'll see that the return type is Object. That's because ArrayList has no idea we've added Strings. As far as ArrayList is concerned, we've added Object instead.

However, we'll use casting to get it back to a String.

for ( int i = list.size() ; i >= 0 ; i-- )
{
   String s = (String) list.get( i ) ;
   System.out.println( "The string at index " + i + " is " + s ) ;
}
This loop should print
The string at index 4 is elk
The string at index 3 is dog
The string at index 2 is cat
The string at index 1 is bat
The string at index 0 is ape
We assume the loop appears after the 5 strings have been added to list.