Java Reference
In-Depth Information
Providing this method is important because it allows a client to avoid unnecessary
inefficiency. For example, suppose that the list has 10,000 values stored in it and the
client wants to replace the first value with something new. The
set
method does it
very quickly. The alternative would be to call
remove
, which would shift over the
other 9,999 values, and then to call
add
, which would shift the other 9,999 values
back to where they were earlier. Using
set
is much more efficient.
You might think that the introduction of the
set
method breaks encapsulation,
because it allows a client to change a value in the array. But it doesn't really break
encapsulation because you force the client to get this access by calling a method.
This fact allows your method to be in control of the client request. So, for example,
you can call the
checkIndex
method to ensure that the array index is legal.
Another common operation that a client might wish to perform is to empty the
structure of all values. This is referred to as the
clear
operation and can be accom-
plished quickly by resetting the
size
field back to its original value of
0
:
public void clear() {
size = 0;
}
You might imagine that you have to reset all of the array elements back to
0
,but
that's not necessary. You have written the code in such a way that a client can only
get access to array elements 0 through
size - 1
. When
size
is reset to
0
, the client
can't access any of the array elements. The only way those array elements will be used
again is if the client makes calls on the
add
method, in which case the old values will
be overwritten with new values supplied by the client. But just as with the
remove
method, you will find at the end of the chapter that you solve this problem slightly
differently for the generic
ArrayList
class.
The last method we will add is a “bulk add” method called
addAll
that adds all of
the values from a second
ArrayIntList
. It may seem a little odd to have one
ArrayIntList
deal with another
ArrayIntList
, but this actually happens fairly
often. The idea is that the first
ArrayIntList
is supposed to add all of the values
from the second
ArrayIntList
, which means that the header for the method looks
like the following:
public void addAll(ArrayIntList other) {
...
}
You can call the appending
add
method to add values to the list. You just need a
loop that iterates over the values in the second list. You also need to call your
checkCapacity
method to make sure that the array has sufficient capacity to store
these new values:
public void addAll(ArrayIntList other) {
checkCapacity(size + other.size);
Search WWH ::
Custom Search