Java Reference
In-Depth Information
14.1
The
ArrayList
Class
“Well, I'll eat it,” said Alice, “and if it makes me grow larger, I can reach the key;
and if it makes me grow smaller, I can creep under the door; so either way I'll
get into the garden. . . .”
LEWIS CARROLL,
Alice's Adventures In Wonderland
ArrayList
is a class in the standard Java libraries. You can think of an
ArrayList
object as an array that can grow (and shrink) in length while your program is running.
In Java, you can read in the length of an array when the program is running, but once
your program creates an array of that length, it cannot change the length of the array.
For example, suppose you write a program to record customer orders for a mail-order
house, and suppose you store all the orders for one customer in an array of objects of
some class called
Item
. You could ask the user how many items she or he will order,
store the number in a variable called
numberOfItems
, and then create the array
item
with the following statement:
ArrayList
Item[] item =
new
Item[numberOfItems];
But suppose the customer enters
numberOfItems
and then decides to order another
item? There is no way to increase the size of the array
item
. There are ways around
this problem with arrays, but they are all rather complicated.
ArrayList
s serve
the same purpose as arrays, except that an
ArrayList
can change length while the
program is running. So an
ArrayList
could handle the customer's extra order
without any problems.
The class
ArrayList
is implemented using an array as a private instance variable.
When this hidden array is full, a new larger hidden array is created and the data
is transferred to this new array. However, you need not concern yourself with this
implementation detail. All you need to know is how to use the
ArrayList
class, and
we are about to tell you that.
If
ArrayList
s are like arrays but have the nice added feature of being able to
change length, then why don't we just always use
ArrayList
s instead of arrays? It
often seems that every silver lining has a cloud, and this is true of
ArrayList
s as
well. There are three main disadvantages of
ArrayList
s: (1) They are less efficient
than arrays; (2) they do not have the square bracket notation, and so using an
ArrayList
is sometimes notationally more awkward than using ordinary arrays; and
(3) the base type of an
ArrayList
must be class type (or other reference type); it
cannot be a primitive type, such as
int
,
double
, or
char
. For example, if you want
an
ArrayList
of
int
values, you must simulate this structure with an
ArrayList
of
Integer
values, where
Integer
is the wrapper class whose objects simulate
int
values. Automatic boxing and unboxing (as discussed in Chapter 5) make (3) less of a
problem, because an
ArrayList
with base type, for example,
Integer
can, in effect,
store values of type
int
.