Java Reference
In-Depth Information
sure that the array has that capacity. In other words, you'll tell the method, “I need
room for this many elements,” and it will test whether the array has that much room.
If it does not, the method throws an IllegalStateException :
// post: checks that the underlying array has the given capacity,
// throwing an IllegalStateException if it does not
private void checkCapacity(int capacity) {
if (capacity > elementData.length) {
throw new IllegalStateException("exceeds list capacity");
}
}
You can add the following line of code to each of the add methods to check that
the array has the capacity to add one more value to the list:
checkCapacity(size + 1);
You also need to modify the comments to indicate that this exception is thrown.
For example, here is the rewritten appending add method:
// pre : size() < capacity (throws IllegalStateException if not)
// post: appends the given value to the end of the list
public void add(int value) {
checkCapacity(size + 1);
elementData[size] = value;
size++;
}
Several methods specify the index of a value. The get method, for example, is
supposed to return the value at a particular index. If you provide a value that is out-
side the bounds of the underlying array, then the method will throw an
ArrayIndexOutOfBoundsException . This exception is better than nothing, but it
doesn't cover all cases. For example, your list might have a capacity of 100 but have
only 10 values stored in it. The client might try to access a value at index 10 or 11 or
50, and your method will return a result when you'd prefer it to throw an exception to
let the client know that the index is not legal for a list of 10 elements.
In this case, it is better to throw an IndexOutOfBoundsException and to include
the illegal index to let the client see exactly what bad value was passed as a parameter.
There are multiple methods that refer to index values, so it is again useful to
introduce a private method that can be called by each method:
// post: throws an IndexOutOfBoundsException if the given index is
// not a legal index of the current list
private void checkIndex(int index) {
if (index < 0 || index >= size) {
 
Search WWH ::




Custom Search