Java Reference
In-Depth Information
Figure 4.4
Index number
changes following
removal of an item
The general utility of numbering with collections
The use of integer index values to access objects in a collection is something that we will see
over and over again—not just with ArrayList s but also with several different types of collec-
tions. So it is important to understand what we have seen of this so far: that the index values
start at zero; that the objects are numbered sequentially; and that there are usually no gaps in the
index values of consecutive objects in the collection.
Using integer values as indices also makes it very easy to express in program code expressions
such as “the next item” and “the previous item” with respect to an item in the collection. If an item
is at index p , then “the next” one will be at index (p+1) and “the previous” one is now at index
(p-1) . We can also map natural-language selections such as “the first three” to program-related
terminology. For example, “the items at indices 0 , 1 , and 2 ” or “the last four” could be “the items
at indices (list.size()-4) to (list.size()-1) ”. We could even imagine working our way
through the entire collection by having an integer index variable whose value is initially set to
zero and is then successively increased by 1, passing its value to the get method to access each
item in the list in order (stopping when it goes beyond the final index value of the list).
But we are getting a little ahead of ourselves. Nevertheless, in a little while we will see how all
this works out in practice when we look at loops and iteration .
Exercise 4.12 Write a method call to remove the third object stored in a collection called
dates .
Exercise 4.13 Suppose that an object is stored at index 6 in a collection. What will be its
index immediately after the objects at index 0 and index 9 are removed?
Search WWH ::

Custom Search