Java Reference
In-Depth Information
public void findInTitle(String searchString)
{
for(Track track : tracks) {
String title = track.getTitle();
if(title.contains(searchString)) {
System.out.println(track.getDetails());
}
}
}
Exercise 4.35 Add a playCount field to the Track class. Provide methods to reset the
count to zero and to increment it by one.
Exercise 4.36 Have the MusicOrganizer increment the play count of a track whenever
it is played.
Exercise 4.37 Add a further field, of your choosing, to the Track class, and provide acces-
sor and mutator methods to query and manipulate it. Find a way to use this information in your
version of the project; for instance, include it in a track's details string, or allow it to be set via a
method in the MusicOrganizer class.
Exercise 4.38 If you play two tracks without stopping the first one, both will play simulta-
neously. This is not very useful. Change your program so that a playing track is automatically
stopped when another track is started.
4.12
The Iterator type
Iteration is a vital tool in almost every programming project, so it should come as no surprise to
discover that programming languages typically provide a wide range of features that support it,
each with their own particular characteristics suited for different situations.
Concept:
An iterator is an
object that provides
functionality to
iterate over all
elements of a
collection.
We will now discuss a third variation for how to iterate over a collection that is somewhat in the
middle between the while loop and the for-each loop. It uses a while loop to perform the iteration
and an Iterator object instead of an integer index variable to keep track of the position in the list.
We have to be very careful with naming at this point, because Iterator (note the uppercase I ) is
a Java type , but we will also encounter a method called iterator (lowercase i ), so be sure to pay
close attention to these differences when reading this section and when writing your own code.
Examining every item in a collection is so common that we have already seen a special con-
trol structure—the for-each loop—that is custom made for this purpose. In addition, Java's
various collection library classes provide a custom-made common type to support iteration, and
ArrayList is typical in this respect.
The iterator method of ArrayList returns an Iterator object. Iterator is also defined
in the java.util package, so we must add a second import statement to the class file to use it:
import java.util.ArrayList;
import java.util.Iterator;
 
 
Search WWH ::




Custom Search