Java Reference
In-Depth Information
What happened to the value 8 ? It's overwritten with the value 3 . The next time
through the loop list[2] is set to be list[1] :
[0]
[1]
[2]
[3]
[4]
list
3
3
9
7
5
list
3
3
3
7
5
You might say, “Wait a minute . . . list[1] isn't a 3 , it's an 8 .” It was an 8 when
you started, but the first iteration of the loop replaced the 8 with a 3 , and now the 3
has been copied into the spot where 9 used to be.
The loop continues in this way, putting 3 into every cell of the array. Obviously,
that's not what you want. To make this code work, you have to run the loop in reverse
order (from right to left instead of left to right). So let's back up to where we started:
[0]
[1]
[2]
[3]
[4]
list
3
8
9
7
5
We tucked away the final value of the list into a local variable. That frees up the
final array position. Now, assign list[4] to be what is in list[3] :
[0]
[1]
[2]
[3]
[4]
list
3
8
9
7
5
list
3
8
9
7
7
This wipes out the 5 that was at the end of the list, but that value is safely stored
away in a local variable. And once you've performed this assignment statement, you
free up list[3] , which means you can now set list[3] to be what is currently in
list[2] :
[0]
[1]
[2]
[3]
[4]
list
3
8
9
7
7
list
3
8
9
9
7
 
Search WWH ::




Custom Search