Java Reference
In-Depth Information
We saw in Chapter 7 that we can use code like the following to accomplish the
shifting task:
for (int i = index; i < size; i++) {
elementData[i] = elementData[i + 1];
}
This code is almost correct. The problem is that the loop executes once too often.
As we have noted, you want to shift values into indexes 1, 2, and 3. But when the
size is 5 , as in our example, the loop will do one extra shift, shifting a value into
index 4. You want to stop the loop one step earlier so that it won't perform this final
shift. You can accomplish that by subtracting one from the final loop bound:
for (int i = index; i < size - 1; i++) {
elementData[i] = elementData[i + 1];
}
This modification almost completes the method. The only other detail you need to
worry about is that once you have removed this value, you need to decrement the size
of the list. Here is the complete method:
public void remove(int index) {
for (int i = index; i < size - 1; i++) {
elementData[i] = elementData[i + 1];
}
size--;
}
Let's take a look at the final state of the list in our example. After we have
removed the value at index 1, shifted three values left, and decremented the size, we
end up with the following list:
occupied
vacant
[0]
[1]
[2]
[3]
[4]
[5]
[6] [7] [...][99]
elementData
12
8
73
14
14
0
0
0
...
0
size
4
Notice that the first cell among the vacant cells has the value 14 in it. You might
imagine that you have to set it back to 0 . In general, this isn't necessary for your
ArrayIntList . Because the value is among the vacant cells, you know that it isn't a
real value of the list. And if you ever need to use that cell again, you'll overwrite the
14 with some new value. It doesn't matter whether you overwrite a 14 or overwrite a
0 . In fact, in the final version of our program, we'll make sure that a client can't ever
Search WWH ::




Custom Search