Java Reference
In-Depth Information
Creating and Naming an
ArrayList
Object
An object of the class
ArrayList
is created and named in the same way as any other object,
except that you specify the base type of the
ArrayList
.
SYNTAX
ArrayList<
Base_Type
>
Object_Name
=
new
ArrayList<
Base_Type
>();
ArrayList<
Base_Type
>
Object_Name
=
new
ArrayList<
Base_Type
>(
Initial_Capacity
);
The
Base_Type
must be a reference type, usually a class type; it cannot be a primitive type
such as
int
or
double
. When a number is given as an argument to the constructor, that
number determines the initial capacity of the
ArrayList
.
EXAMPLES
ArrayList<String> list =
new
ArrayList<String>();
ArrayList<Double> list2 =
new
ArrayList<Double>(30);
If you would use
String temp = a[index];
for an array of strings
a
, then the analogous statement for a suitable
ArrayList
named
list
would be
String temp = list.get(index);
Accessing at an Index
If
list
is an
ArrayList
, its elements can be accessed as follows:
EXAMPLES
ArrayList<String> list =
new
ArrayList<String>();
int
index;
...
list.set(index, "Here");
//Sets the element
//at index to "Here".
String temp = list.get(index);
//The expression
//list.get(index) returns the element at position index.
ArrayList<Integer> list2 =
new
ArrayList<Integer>();
...
(continued)