Java Reference
In-Depth Information
Chapter 15
1. An array list's size is the number of elements that have been added to it. Its capacity is
the length of its internal array. The size is always less than or equal to the capacity.
2. The ArrayIntList class keeps an array of elements and a size. The array is
necessary because it is where we store the data inside the collection. The size is
necessary because some of the elements at the end of the array may not be mean-
ingful values. If we removed the size field, we would not know how many
elements were meaningful.
3. If the fields were static, all lists would share the same array and size. Any modifi-
cation to one list would also be seen in all other lists. The client's output would be
the following:
[1, 82, 97, 7, -8]
[1, 82, 97, 7, -8]
4. In this version of the list class, if the client tries to add too many values, the code
crashes with an out-of-bounds exception.
5. We use a toString method because this is the standard way of printing objects in
Java. It is also more versatile than a print method because it can print the text rep-
resentation of the list to any target, such as a file or GUI.
6. Having accessor methods such as size is better than making the fields public
because it preserves the encapsulation of the object. As we discussed in Chapter 8,
this format improves the cleanliness of the abstraction of the object and would
allow us to change the implementation later if we desired.
7. It is most expensive to insert or remove elements at the beginning of the list,
because all the elements must be shifted to the right by one index.
8. public int min() {
if (size == 0) {
throw new IllegalStateException();
}
int minValue = elementData[0];
for (int i = 1; i < size; i++) {
minValue = Math.min(minValue, elementData[i]);
}
return minValue;
}
public int max() {
if (size == 0) {
throw new IllegalStateException();
}
int maxValue = elementData[0];
 
Search WWH ::




Custom Search