Java Reference
In-Depth Information
Exercise 4.6
Write a declaration of a private field called
tracks
for storing a collection of
MusicTrack
objects.
Exercise 4.7
Write assignments to the
library, cs101,
and
track
variables (which
you defined in the previous three exercises) to create the appropriate
ArrayList
objects.
Write them once without using diamond notation and once with diamond notation if you are
using a Java 7 compiler.
Generic classes are used for a variety of purposes; we will encounter more of them later in the
book. For now, collections such as
ArrayList
, and some other collections that we shall en-
counter shortly, are the only generic classes we need to deal with.
4.7
Numbering within collections
When exploring the
music-organizer-v1
project in the first few exercises, we noted that it was
necessary to use parameter values starting at 0 to list and remove file names in the collection.
The reason behind this requirement is that items stored in
ArrayList
collections have an im-
plicit numbering, or positioning, that starts from 0. The position of an object in a collection is
more commonly known as its
index.
The first item added to a collection is given index number
0, the second is given index number 1, and so on. Figure 4.3 illustrates the same situation as
above, with index numbers shown in the
ArrayList
object.
It is important to be aware that this means that the last item in a collection has the index
size-1
.
For example, in a list of 20 items, the last one will be at index 19.
Figure 4.3
Index numbers of
elements in a
collection
P
\0XVLF
0XVLF2UJDQL]HU
$U
UD\/LVW6WULQJ!
ILOHV
6WULQJ
6WULQJ
6WULQJ
³0RUQLQJ%OXHVPS´
³'RQW*RPS´
³0DWFK%R[%OXHVPS´
Search WWH ::
Custom Search