Java Reference
In-Depth Information
14.1
The
Class
ArrayList
“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
is a class in the standard Java libraries. You can think of an
ArrayList
ArrayList
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
. You could ask the user how many items she or he will order,
store the number in a variable called
Item
, and then create the array
numberOfItems
item
with the following statement:
Item[] item = new Item[numberOfItems];
But suppose the customer enters
and then decides to order another
item? There is no way to increase the size of the array
numberOfItems
. There are ways around this
item
problem with arrays, but they are all rather complicated.
s serve the same pur-
ArrayList
pose as arrays, except that an
can change length while the program is run-
ArrayList
ning. So an
could handle the customer's extra order without any problems.
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 imple-
mentation detail. All you need to know is how to use the
The class
ArrayList
class, and we are
ArrayList
about to tell you that.
If
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 that is true of
ArrayList
s as well. There are
ArrayList
three main disadvantages of
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,
ArrayList
such as
,
, or
. For example, if you want an
of
values, you
int
double
char
ArrayList
int
must simulate this structure with an
of
values, where
is
ArrayList
Integer
Integer
the wrapper class whose objects simulate
values. Automatic boxing and unboxing
(as discussed in Chapter 5) makes (3) less of a problem, since an
int
with base
ArrayList
type, for example,
can, in effect, store values of type
.
Integer
int
Search WWH ::




Custom Search