Java Reference
In-Depth Information
Using the
Class
ArrayList
are used in much the same way as arrays, but there are some important
differences. First, the definition of the class
ArrayLists
is not provided automatically.
import
statement
ArrayList
The definition is in the package
, and any code that uses the class
java.util
ArrayList
must contain the following, normally at the start of the file:
import
java.util.ArrayList;
An
ArrayList
is created and named in the same way as objects of any class, except
that you specify the base type using a new notation. For example,
ArrayList<String> list =
new
ArrayList<String>(20);
This statement makes
list
the name of an
ArrayList
that stores objects of the class
String
and that has an
initial
capacity
of 20 items. When we say that an
ArrayList
has
a certain capacity, we mean that it has been allocated memory for that many items, but if
it needs to hold more items, the system will automatically allocate more memory. By care-
fully choosing the initial capacity of an
ArrayList
, you can often make your code more
efficient, but this capacity has no effect on how many items the
ArrayList
can hold. If
you choose your capacity to be large enough, then the system will not need to reallocate
memory too often, and as a result, your program should run faster. On the other hand, if
you make your capacity too large, you will waste storage space. However, no matter what
capacity you choose, you can still do anything you want with the
ArrayList
.
The type
String
in the previous
ArrayList
example is the
base type
of the
ArrayList
class. An
ArrayList
, that is, an object of the
ArrayList
class, stores objects of its base
type. You can use any reference type as the base type of an
ArrayList
class. In particu-
lar, you can use any class or interface type. However, you cannot use a primitive type,
such as
int
or
double
, as the base type of an
ArrayList
class. This is an example of a
type parameter. The
ArrayList
class is defined as having a type parameter for the type
of the elements in the list. You create a concrete class by specifying, in angular brack-
ets, a class type to be substituted for this type parameter. For example, the following
code, which we saw earlier, substitutes the type
String
for the type parameter to create
the class
ArrayList<String>
and an object of this class named
list
:
capacity
base type
ArrayList<String> list =
new
ArrayList<String>(20);
ArrayList
objects can be used like arrays, but they do not have the array square-
bracket notation. If you would use
a[index] = "Hi Mom!";
for an array of strings
a
, then the analogous statement for a suitable
ArrayList
named
list
would be
set
list.set(index, "Hi Mom!");