ArrayLists and Iterators
6. Example Program Continued
Answer:
The list will hold references to Integer
objects.
Example Program Continued
import java.util.* ; public class ArrayListEg { public static void main ( String[] args) { // Create an ArrayList that holds references to String ArrayList<String> names = new ArrayList<String>(); // Add three String references names.add("Amy"); names.add("Bob"); names.add("Cindy"); // Access and print out the three String Objects System.out.println("element 0: " + names.get(0) ); System.out.println("element 1: " + names.get(1) ); System.out.println("element 2: " + names.get(2) ); } } |
In the program, the ArrayList
holds references of type String
or a subclass of String
.
In the picture, three elements have been added. The references are added in order starting with cell 0 of the array.
Then the program accesses the references using the get()
method and prints out the String
s. The output of the program is:
element 0: Amy
element 1: Bob
element 2: Cindy
The names.get( int index )
method returns the reference in the cell at index
. If the cell is empty, an IndexOutOfBoundsException
will be thrown and the program will halt (unless
there is code to handle the exception.)
Question 6:
Suppose that the following follows the first three
add
statements:names.add("Daniel");
Where will the reference to "Daniel" be added?