ArrayLists and Iterators

Read this chapter about lists and the useful methods that are available for adding and inserting elements into a list. 

7. Constructors for ArrayList Objects


Answer:

A reference to "Daniel" will be added to cell 3 of the array (right after the reference to "Cindy").

Constructors for ArrayList Objects

To declare a reference variable for an ArrayList do this:

ArrayList<E> myArray;  

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.

Construct the ArrayList later on in the code:

myArray = new ArrayList<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 the capacity needed, start the ArrayList with that capacity.

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 can expand beyond this capacity if you add more elements. 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.

Question 7:

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.

ArrayList students = new ArrayList( ) ;