Java Reference
In-Depth Information
One final issue has to do with memory allocation. Consider what happens when a
value is removed from the simple ArrayIntList . An array element that used to cor-
respond to a list element is no longer being used. In general, this isn't a problem, and
we haven't bothered to do any cleaning up afterwards. For example, suppose that you
have a list with a capacity of 10 and you store the values [10, 20, 30, 40] in the
list. The array looks like this:
[0]
[1]
[2]
[3]
[4]
[5]
[6] [7] [8] [9]
elementData
10
20
30
40
0
0
0
0
0
0
size
4
If you then remove the value at index 0 , you shift the other three values left and
decrement size :
[0]
[1]
[2]
[3]
[4]
[5]
[6] [7] [8] [9]
elementData
20
30
40
40
0
0
0
0
0
0
size
3
Notice that you now have two occurrences of 40 in the list. That isn't generally a
problem because you know from the value of your size field that the 40 stored in
index 3 isn't being used.
You can't be so cavalier when it comes to objects. We have to think about what is
known as the garbage collector :
Garbage Collector
A process that is part of the Java runtime environment that periodically
frees the memory used by objects that are no longer referenced.
In some programming languages, you have to explicitly destroy objects when you
don't need to use them any longer. Java saves you the trouble of doing this. Instead,
its garbage collector looks for objects that are no longer being used (i.e., objects that
are no longer referenced). You want to make sure that your ArrayList doesn't inter-
fere with what the garbage collector is trying to accomplish.
If your ArrayList is keeping a reference to some object that is no longer being
used, then the garbage collector might not recognize that it can reclaim that space. So
you have to explicitly set that array element back to null .
A direct translation of the code produces the following remove method:
public void remove(int index) {
checkIndex(index);
for (int i = index; i < size - 1; i++) {
 
Search WWH ::




Custom Search