Java Reference
In-Depth Information
throw new IndexOutOfBoundsException("index: " + index);
}
}
This private method will properly throw an exception for
get
and
remove
. It isn't
quite the right test to use for the
add
method that takes an index as a parameter,
because
add
has a slightly different precondition than the other methods. Normally, it
doesn't make sense to refer to a value at index
size
because that index is beyond the
last value stored in the list. For example, if the list stores 10 values, then you don't
want to call
get
or
remove
for a nonexistent value at index 10. But for
add
, it makes
sense to refer to this index. If there are currently 10 values in the list, then you would
be allowed to add a new value at index 10 because it is a new value not currently in
the list. Instead of calling the private method, the
add
method will have its own code
for checking the index and throwing an
IndexOutOfBoundsException
.
There is a further benefit to adding all of this code to throw exceptions: Adding the
code will ensure that your object is never in a corrupt state. It will always satisfy certain
data invariants. (Data invariants were described in Chapter 8.) In particular, you know that
•
size
<=
elementData.length
always (your calls on
checkCapacity
make
sure of that)
•
the array elements that you examine are always in the range of 0 to
size - 1
(your calls on
checkIndex
make sure of that)
•
your code will never generate an
ArrayIndexOutOfBoundsException
It is extremely useful to know that your class will always satisfy these constraints.
This knowledge is an added benefit of encapsulation. If a client could reach in
and change the
size
or
elementData
fields, then you couldn't make these kind of
guarantees.
The built-in
ArrayList<E>
class has many other methods besides the ones we have
implemented so far, so it makes sense to go ahead and add some of those methods to
your
ArrayIntList
class. These methods are largely for the convenience of the client,
since you could achieve the same functionality by calling existing methods on the list.
Your class has a method called
indexOf
that can be used to search for the location
of a value in the list. Sometimes, though, a client just wants to ask the simpler question
of whether a particular value appears in the list somewhere. The convention in Java is to
use a method called
contains
for this purpose. It has a
boolean
return type:
public boolean contains(int value) {
...
}
Search WWH ::
Custom Search