Java Reference
In-Depth Information
Like an Array, but More Dynamic
Problem
You don't want to worry about storage reallocation; you want a standard class to handle it for
you.
Solution
Use an
ArrayList
.
Discussion
The first of the
Collections
classes we will discuss,
ArrayList
is a standard class from
java.util
that encapsulates the functionality of an array but allows it to expand automatic-
ally. You can just keep on adding things to it, and each addition behaves the same. If you
watch
really
closely, you might notice a brief extra pause once in a while when adding ob-
jects as the
ArrayList
reallocates and copies. But you don't have to think about it.
However, because
ArrayList
is a class and isn't part of the syntax of Java, you can't use
Java's array syntax; you must use methods to access the
ArrayList
's data. It has methods to
add objects, retrieve objects, find objects, and tell you how big the
List
is and how big it can
become without having to reallocate (note that the
ArrayList
class is but one implementa-
tion of the
List
interface; more on that later). Like the other collection classes in
java.util
,
ArrayList
's storing and retrieval methods were originally defined to have parameters and
return values of
java.lang.Object
. Because
Object
is the ancestor of every defined type,
you can store objects of any type in a
List
(or any collection) and cast it when retrieving it.
If you need to store a small number of built-ins (like
int
,
float
, etc.) into a collection con-
taining other data, use the appropriate wrapper class (see the Introduction to
Chapter 5
). To
store
boolean
s, either store them directly in a
java.util.BitSet
(see the online document-
ation) or store them in a
List
using the
Boolean
wrapper class.
Because
Object
is usually too general for accurate work, all modern versions of Java
provide the “generic types” mechanism described in
Using Generic Collections
. So
nowadays, you declare an
ArrayList
(or other collection) with a “type parameter” in angle
brackets, and the parameters and returns are treated as being of that type, ensuring that ob-