Java Reference
In-Depth Information
Technically, we can also remove elements by using the collection's get method with an index
for the iteration. This is not recommended, however, because the element indices can change
when we add or delete elements and it is quite easy to get the iteration with indices wrong when
we modify the collection during iteration. Using an Iterator protects us from such errors.
Exercise 4.39 Implement a method in your music organizer that lets you specify a string as
a parameter and then removes all tracks whose titles contain that string.
Summary of the music-organizer project
In the music organizer we have seen how we can use an ArrayList object, created from a
class out of the class library, to store an arbitrary number of objects in a collection. We do not
have to decide in advance how many objects we want to store, and the ArrayList object auto-
matically keeps track of the number of items stored in it.
We have discussed how we can use a loop to iterate over all elements in the collection. Java has
several loop constructs—the two we have used here are the for-each loop and the while loop.
We typically use a for-each loop when we want to process the whole collection and the while
loop when we cannot predetermine how many iterations we need or when we need to remove
elements during iteration.
With an ArrayList , we can access elements either by index or we can iterate over all ele-
ments using an Iterator object. It will be worthwhile for you to review the different circum-
stances under which the different types of loop (for-each and while) are appropriate and why an
Iterator is to be preferred over an integer index, because these sorts of decisions will have
to be made over and over again. Getting them right can make a big difference to the ease with
which a particular problem can be solved.
Exercise 4.40 Use the club project to complete the following exercises. Your task is to
complete the Club class, an outline of which has been provided in the project. The Club
class is intended to store Membership objects in a collection.
Within Club , define a field for an ArrayList . Use an appropriate import statement for this
field, and think carefully about the element type of the list. In the constructor, create the col-
lection object and assign it to the field. Make sure that all the files in the project compile before
moving on to the next exercise.
Exercise 4.41 Complete the numberOfMembers method to return the current size of the
collection. Until you have a method to add objects to the collection, this will always return zero,
of course, but it will be ready for further testing later.
Exercise 4.42 Membership of a club is represented by an instance of the Membership
class. A complete version of Membership is already provided for you in the club project, and
it should not need any modification. An instance contains details of a person's name and the
Search WWH ::

Custom Search