Java Reference
In-Depth Information
This insertion is similar to the remove operation. You want to deal with cells between
the target index (where the new value is to be added) and the end of the sequence of
occupied cells. Therefore, you know that the loop bounds will be something like the
following:
for (int i = index; i < size; i++) {
...
}
We saw in Chapter 7 that you can shift values to the right by writing code like the
following :
for (int i = index; i < size; i++) {
elementData[i] = elementData[i - 1];
}
There are several problems with this code. First, it starts too early. In the example,
you are trying to shift values so that you can add a new value at index 2. The first
shift you want to do is to shift the value that is currently at index 2 into index 3. But
the preceding loop will first shift the value at index 1 into index 2. The loop needs to
start one index later:
for (int i = index + 1; i < size; i++) {
elementData[i] = elementData[i - 1];
}
Even after you make this change, the loop bounds are still not correct. In the sam-
ple for a list of 5 elements, the final shift moved a value into the cell with index 5.
The preceding code will stop the loop once i is 4 (while it is still strictly less than the
size). The loop needs to allow i to be equal to the size:
for (int i = index + 1; i <= size; i++) {
elementData[i] = elementData[i - 1];
}
The final problem, as described in detail in Chapter 7, is that this loop has to be
run backwards rather than forwards. Otherwise you overwrite your list values with
the value that is stored at the target index:
for (int i = size; i >= index + 1; i--) {
elementData[i] = elementData[i - 1];
}
Search WWH ::




Custom Search