Java Reference
In-Depth Information
5.6 The ArrayList Class
Now that we have a loop in our arsenal of programming statements, let's introduce a
very useful class for managing a set of objects. The ArrayList class is part of the java.
util package of the Java standard class library. An ArrayList object stores a list of
objects and allows you to refer to each one by an integer index value. We will often use
loops to scan through the objects in the list and deal with them in one way or another.
Internally, the ArrayList class manages the list using a program-
ming construct called an array (hence the name). Arrays are discussed
in detail in Chapter 8, but we don't have to know the details of arrays
to make use of an ArrayList object. The ArrayList class is part of
the Java Collections API, a group of classes that serve to organize and
manage other objects. We discuss collection classes further in Chapter 13.
Figure 5.8 lists several methods of the ArrayList class. You can add and
remove elements in various ways, determine if the list is empty, and obtain the
number of elements currently in the list, among several other operations.
Note that the ArrayList class refers to having elements of type E . That is a generic
type (the E stands for element), which is determined when an ArrayList object is cre-
ated. So you don't just create an ArrayList object, you create an ArrayList object that
will store a particular type of object. The type parameter for a given object is written
in angle brackets after the class name. So we can talk about an ArrayList<String>
object that manages a list of String objects, or an ArrayList<Book> that manages a
list of Book objects.
KEY CONCEPT
An ArrayList object stores a list
of objects and lets you access them
using an integer index.
You can create an ArrayList without specifying the type of ele-
ment, in which case the ArrayList stores Object references, which
means that you can put any type of object in the list. This is usually not
a good idea. The point of being able to commit to storing a particular
type in a given ArrayList object lets the compiler help you check that
only the appropriate types of objects are being stored in the object.
KEY CONCEPT
When an ArrayList object is cre-
ated, you specify the type of element
that will be stored in the list.
The index values of an ArrayList begin at 0, not 1. So conceptually, for
example, an ArrayList of String objects might be managing the following list:
0 "Bashful"
1 "Sleepy"
2 "Happy"
3 "Dopey"
4 "Doc"
Also note that an ArrayList stores references to objects. You cannot cre-
ate an ArrayList that stores primitive values such as an int . But that's where
wrapper classes come to the rescue again. For example, you can create an
ArrayList<Integer> or an ArrayList<Double> as appropriate.
 
Search WWH ::




Custom Search