Index | 0 | 1 | 2 | 3 | 4 |
Value | "ape" | "bat" | "cat" | "dog" | "elk" |
Index | 0 | 1 | 2 | 3 | 4 |
Value | "elk" | "dog" | "cat" | "bat" | "ape" |
This is where you need to sit and think.
Here's the code:
public ArrayList reverse( ArrayList orig ) { ArrayList reversed = new ArrayList() ; for ( int i = orig.size() - 1 ; i >= 0 ; i-- ) { Object obj = orig.get( i ) ; reversed.add( obj ) ; } return reversed ; }Trace the code where orig has the contents of the ArrayList at the beginning of this lesson, to see if reversed has the contents in reverse.
This sounds like swapping. And it is!
To describe what we're going to do, we'll write out pseudocode. Pseudocode is like an outline. It's not real Java code, but it's not hard to make it real Java code.
Here's an example:
Let's write the code, and trace to see if it works:
public static void reverse( ArrayList list ) { for ( int start = 0, end = list.size() - 1 ; start < list.size() ; start++, end-- ) { swap( list, start, end ) ; } } private static void swap( ArrayList alist, int front, int back ) { Object temp = alist.set( front, alist.get( back ) ) ; alist.set( back, temp ) ; }Reread the section about comma operators to understand the for loop above.
Let's trace out the code. We print out the ArrayList after the completion of each iteration, starting at iteration 0.
Index | 0 | 1 | 2 | 3 | 4 |
Value | "elk" | "bat" | "cat" | "dog" | "ape" |
Index | 0 | 1 | 2 | 3 | 4 |
Value | "elk" | "dog" | "cat" | "bat" | "ape" |
Index | 0 | 1 | 2 | 3 | 4 |
Value | "elk" | "dog" | "cat" | "bat" | "ape" |
Index | 0 | 1 | 2 | 3 | 4 |
Value | "elk" | "bat" | "cat" | "dog" | "ape" |
Index | 0 | 1 | 2 | 3 | 4 |
Value | "ape" | "bat" | "cat" | "dog" | "elk" |
Let's rewrite the code, this time correctly.
public static void reverse( ArrayList list ) { for ( int start = 0, end = list.size() - 1 ; start < end ; start++, end-- ) { swap( list, start, end ) ; } }Alternatively, we can just go halfway through the list.
public static void reverse( ArrayList list ) { for ( int start = 0, end = list.size() - 1 ; start < list.size() / 2; start++, end-- ) { swap( list, start, end ) ; } }Notice that when list.size() is odd, the result truncates. For example, we had list.size() equal to 5, so 5 / 2, using integer division is 2. Thus, start starts at 0, then 1, then when it reaches 2, we exit the loop. That way, we don't swap the middle element with itself.
The code also works when list.size() is even. Suppose the size was 6, then 6 / 2 evaluates to 3. first then has values 0, 1, and 3, and exits when it reaches 3.