Java Reference
In-Depth Information
see that extra value of 14 . The situation is slightly different when you deal with the
generic ArrayList , but we'll save that discussion for the end of the chapter.
Another operation that a client is likely to want to perform is to add a value in the
middle of a list. You already wrote a simple add method that appends at the end of
the list:
public void add(int value) {
...
}
You can call the new method add as well, but it will have different parameters.
You will still need to know the value to add, as with the appending method. But this
new method will also need to know the index where the new value is to be added.
Thus, it will look like the following:
public void add(int index, int value) {
...
}
Implementing this method is more complicated than appending a value at the end
of the list because you have to shift values over to make room for the value to be
inserted. Suppose, for example, that your list contains the five values [3, 6, 9,
12, 15] :
occupied
vacant
[0]
[1]
[2]
[3]
[4]
[5]
[6] [7] [...][99]
elementData
3
6
9
12
15
0
0
0
...
0
size
5
Suppose that you want to insert the value 7 at index 2. That insertion will require
you to shift each of the values that are currently in indexes 2 through 4 to the right
by one:
[0]
[1]
[2]
[3]
[4]
[5]
[6] [7] [...][99]
elementData
3
6
9
12
15
0
0
0
...
0
elementData
3
6
9
9
12
15
0
0
...
0
 
Search WWH ::




Custom Search