Java Reference
In-Depth Information
The listFile and removeFile methods both illustrate the way in which an index number is
used to gain access to an item in an ArrayList : one via its get method and the other via its
remove method. Note that both methods make sure that their parameter value is in the range of
valid index values [0...size()-1] before passing the index on to the ArrayList methods.
This is a good stylistic validation habit to adopt, as it prevents failure of a library-class method
call when passing on parameter values that could be invalid.
Pitfall If you are not careful, you may try to access a collection element that is outside the valid
indices of the ArrayList . When you do this, you will get an error message and the program will
terminate. Such an error is called an index-out-of-bounds error. In Java, you will see a message
about an IndexOutOfBoundsException .
Exercise 4.8 If a collection stores 10 objects, what value would be returned from a call to
its size method?
Exercise 4.9 Write a method call using get to return the fifth object stored in a collection
called items.
Exercise 4.10 What is the index of the last item stored in a collection of 15 objects?
Exercise 4.11 Write a method call to add the object held in the variable favoriteTrack
to a collection called files .
4.7.1
The effect of removal on numbering
As well as adding items to a collection, it is common to want to remove items, as we saw
with the removeFile method in Code 4.1. The ArrayList class has a remove method that
takes the index of the object to be removed. One detail of the removal process to be aware
of is that it can change the index values at which other objects in the collection are stored.
If an item with a low index number is removed, then the collection moves all subsequent
items along by one position to fill in the gap. As a consequence, their index numbers will be
decreased by 1.
Figure 4.4 illustrates the way in which some of the index values of items in an ArrayList
are changed by the removal of an item from the middle of the list. Starting with the situa-
tion depicted in Figure 4.3, the object with index 1 has been removed. As a result, the object
originally at index number 2 has changed to 1, whereas the object at index number 0 remains
unchanged.
Furthermore, we shall see later that it is possible to insert items into an ArrayList at a posi-
tion other than right at the end of it. This means that items already in the list may have their
index numbers increased when a new item is added. Users have to be aware of this possible
change of indices when adding or removing elements.
 
Search WWH ::




Custom Search