go to previous page   go to home page   go to next page

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
                             // that will hold references to objects of type E 
                             // "E" stands for any class name, for eg. "String"

The future ArrayList object will contain an array of references to objects of type E or to a descendant class of 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. 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( ) ;