Java Reference
In-Depth Information
return i;
}
}
return -1;
}
You haven't yet given the client the ability to remove a value from the list. Let's
call the method remove . It should take as a parameter the index of the value to be
removed:
public void remove(int index) {
...
}
Suppose, for example, that a list contains the five values [12, 19, 8, 73, 14] :
occupied
vacant
[0]
[1]
[2]
[3]
[4]
[5]
[6] [7] [...][99]
elementData
12
19
8
73
14
0
0
0
...
0
size
5
Suppose that you want to remove the value 19 , which is stored at index 1. This
action will create a gap in the list unless you shift values over to fill in the gap. The
three values that come after the value 19 each have to be shifted down by one position:
[0]
[1]
[2]
[3]
[4]
[5]
[6] [7] [...][99]
elementData
12
19
8
73
14
0
0
0
...
0
elementData
12
8
73
14
14
0
0
0
...
0
In order to shift the values over, you obviously need some kind of loop. You want
to shift a value into index 1, another value into index 2, and another value into index 3.
Why start at index 1? Because that's the target index, the index of the value you've
been asked to remove. And why stop at index 3? Because that's when you run out of
occupied cells to shift. The following code is a good first guess at the loop bounds:
for (int i = index; i < size; i++) {
...
}
 
Search WWH ::




Custom Search