Java Reference
In-Depth Information
This loop is almost the right answer, but it has an off-by-one bug. This loop will
execute five times for the sample array, but you only want to shift four values (you
want to do the assignment for i equal to 0 , 1 , 2 , and 3 , but not for i equal to 4 ). So,
this loop goes one too many times. On the last iteration of the loop, when i is equal
to 4 , the loop executes the following line of code:
list[i] = list[i + 1];
This line becomes:
list[4] = list[5];
There is no value list[5] because the array has only five elements, with indexes
0 through 4. So, this code generates an ArrayIndexOutOfBoundsException . To fix
the problem, alter the loop so that it stops one iteration early:
for (int i = 0; i < list.length - 1; i++) {
list[i] = list[i + 1];
}
In place of the usual list.length , use (list.length - 1) . You can think of the
minus one in this expression as offsetting the plus one in the assignment statement.
Of course, there is one more detail you must address. After shifting the values to
the left, you've made room at the end of the list for the value that used to be at the
front of the list (which is currently stored in a local variable called first ). When the
loop has finished executing, you have to place this value at index 4:
list[list.length - 1] = first;
Here is the final method:
public static void rotateLeft(int[] list) {
int first = list[0];
for (int i = 0; i < list.length - 1; i++) {
list[i] = list[i + 1];
}
list[list.length - 1] = first;
}
An interesting variation on this method is to rotate the values to the right instead
of rotating them to the left. To perform this inverse operation, you want to take the
value that is currently at the end of the list and bring it to the front, shifting the
remaining values to the right. So, if a variable called list initially stores the values
(3, 8, 9, 7, 5), it should bring the 5 to the front and store the values (5, 3, 8, 9, 7).
Begin by tucking away the value that is being rotated into a temporary variable:
int last = list[list.length - 1];
 
Search WWH ::




Custom Search