A reference to "Daniel" will be added to cell 3 of the array.
ArrayList
Objects
To declare a reference variable for an ArrayList
, do the following.
The futue ArrayList
object will contain an array of references to
objects of type E
.
ArrayList<E> myArray; // myArray is a reference to a future ArrayList object // that will hold references to objects of type E
To declare a reference variable and to construct an ArrayList
, do this:
ArrayList<E> myArray = new ArrayList<E>(); // myArray is a reference to an ArrayList // that holds references to objects of type E
The array has an initial capacity of 10 cells, although the capacity will increase as
needed as references are added to the list.
Cells will contain references to objects of type E
(or a descendant class).
This may not be very efficient.
If you have an idea of what the capacity you need,
start the ArrayList
with that capacity.
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 can expand beyond this capacity if you add more elements.
Expanding the capacity of an ArrayList
is slow;
and will slow down your program if it happens too often.
To avoid this, estimate how many elements will be 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 often a few students are added during the first few weeks of the semester,
and sometimes some students drop.
Data for a student is kept in a Student
object.
Declare and construct a ArrayList
suitable for this situation.