Java Reference
In-Depth Information
Then shift the other values to the right:
[0]
[1]
[2]
[3]
[4]
list
3
8
9
7
5
list
3
3
8
9
7
In this case, the four individual assignment statements would be the following:
list[1] = list[0];
list[2] = list[1];
list[3] = list[2];
list[4] = list[3];
A more general way to write this is the following line of code:
list[i] = list[i - 1];
If you put this code inside the standard
for
loop, you get the following:
// doesn't work
for (int i = 0; i < list.length; i++) {
list[i] = list[i - 1];
}
There are two problems with this code. First, there is another off-by-one bug.
The first assignment statement you want to perform would set
list[1]
to contain
the value that is currently in
list[0]
, but this loop sets
list[0]
to
list[-1]
.
Java generates an
ArrayIndexOutOfBoundsException
because there is no value
list[-1]
. You want to start
i
at
1
, not
0
:
// still doesn't work
for (int i = 1; i < list.length; i++) {
list[i] = list[i - 1];
}
However, this version of the code doesn't work either. It avoids the exception, but
think about what it does. The first time through the loop it assigns
list[1]
to what
is in
list[0]
:
[0]
[1]
[2]
[3]
[4]
list
3
8
9
7
5
list
3
3
9
7
5
Search WWH ::
Custom Search