Java Reference
In-Depth Information
its two fields, here we see the constructor of the MusicOrganizer creating an object of type
ArrayList<String> and storing it in the files field.
4.4.2
Diamond notation
Note that when creating the ArrayList instance, we have specified the complete type again
with the element type in angle brackets, followed by parentheses for the (empty) parameter list:
files = new ArrayList<String>();
In all versions of Java prior to version 7, using the full form of the generic type when creating
an instance was a necessity, but from Java 7 onwards it is possible for the Java compiler to infer
the parameterized type of the object being created from the type of the variable being assigned
to. This allows us to use the so-called diamond notation as follows:
files = new ArrayList<>();
Using this form doesn't change the fact that the object being created will only be able to store
String objects; it is just a convenience for the programmer.
In this topic, however, we will retain the older-style notation, both for compatibility with the
majority of Java source code you are likely to see and because, at the time of writing, not every-
one using the topic will have access to a Java 7 compiler.
4.4.3
Key methods of ArrayList
The ArrayList class defines quite a lot of methods, but we shall make use of only four at this
stage, to support the functionality we require: add , size , get , and remove .
The first two are illustrated in the relatively straightforward addFile and getNumberOf-
Files methods, respectively. The add method of an ArrayList stores an object in the list,
and the size method tells us how many items are currently stored in it. We will look at how the
get and remove methods work in Section 4.7, though you will probably get some idea before-
hand simply by reading through the code of the listFile and removeFile methods.
4.5
Object structures with collections
To understand how a collection object such as an ArrayList operates, it is helpful to examine an
object diagram. Figure 4.1 illustrates how a MusicOrganizer object might look with two filename
strings stored in it. Compare Figure 4.1 with Figure 4.2, where a third file name has been stored.
There are at least three important features of the ArrayList class that you should observe:
It is able to increase its internal capacity as required: as more items are added, it simply
makes enough room for them.
It keeps its own private count of how many items it is currently storing. Its size method
returns that count.
It maintains the order of items you insert into it. The add method stores each new item at the
end of the list. You can later retrieve them in the same order.
 
 
Search WWH ::




Custom Search