Java Reference
In-Depth Information
for (int i = 0; i < other.size; i++) {
add(other.elementData[i]);
}
}
This code refers to other.size and other.elementData , which you might
imagine would generate an error because they are private fields. In fact, the code does
not generate an error. Recall from the Chapter 8 examples that the word private means
that it is “private to the class.” This is not the way that we as humans understand the
meaning of private. (If something is private to me, then it shouldn't be available to
other humans.) But in Java, one ArrayIntList object can access private elements of
another ArrayIntList object because they both belong to the same class.
You can find the complete third version of the ArrayIntList class on the web
page http://buildingjavaprograms.com.
15.3 Advanced Features
In this section we explore adding some extra advanced functionality to the
ArrayIntList class. First we will see how to implement the class so that it has no
fixed capacity and will grow larger if necessary. Then we will learn how to provide
an iterator over the list.
Resizing When Necessary
The built-in ArrayList<E> class has a notion of capacity, as does our ArrayIntList
class. But instead of throwing an exception when the capacity is exceeded, the class
creates a larger array. In other words, its capacity grows as needed to accommodate
the addition of new values to the list.
It isn't generally easy to make an array bigger. Java doesn't allow you to stretch an
array that was constructed previously. Instead, you have to allocate a brand-new array
and copy values from the old array to the new array. An analogy would be the way
shops and other businesses work in the real world. If you need some extra space for
your store, you can't generally break down the wall and grab some of the space from
the store next door. More often, you have to relocate your store to a larger space.
Obviously you don't want to construct a new array too often. For example, sup-
pose you had space for 1000 values and found you needed space for one more. A
poor solution would be to allocate a new array of length 1001 and copy the 1000 val-
ues over. Then, if you find you need space for one more, you could make an array
that is 1002 in length and copy the 1001 old values over. This kind of growth policy
would be very expensive.
A better idea would be to double the size of the array when you run out of space.
If you have filled up an array of length 1000, you double its size to 2000 when the
client adds something more. That particular call on add is expensive because it has to
 
Search WWH ::




Custom Search