A reference to "Daniel" will be added to cell 3 of the array (right after the reference to "Cindy").
ArrayList
Objects
To declare a reference variable for an ArrayList
do this:
ArrayList<E> myArray;
Replace E
with the class you want.
For example, to construct an ArrayList
of references to String
,
do this:
ArrayList<String> stringArray;
myArray
is a reference to a future ArrayList
object.
The future ArrayList
object will contain an array of references to
objects of type E
or to a descendant class of E
.
An ArrayList
object is constructed by:
myArray = new ArrayList<E>();
The initial capacity is 10 cells, although this increases as
needed as references are added to the list.
Cells will contain references to objects of type E
(or a descendant class).
To both declare a reference variable and construct an ArrayList
, do this:
ArrayList<E> myArray = new ArrayList<E>();
To declare a variable and to construct a ArrayList
with a specific
initial capacity do this:
ArrayList<E> myArray = new ArrayList<E>( int initialCapacity );
The initial capacity is the number of cells that the ArrayList
starts with.
It expands beyond this capacity if needed.
Expanding the capacity of an ArrayList
is slow.
To avoid this, estimate how many elements are needed and construct an
ArrayList
of that many plus some extra.
Say that you are writing a program to keep track of the students in a course.
There are usually about 25 students,
but a few students may add the class,
and a few students may drop the class.
Data for a student is kept in a Student
object.
Declare and construct an ArrayList
suitable for this situation.