The list will hold references to Integer
objects.
The names
object of the example program can hold references
to Strings
.
The picture shows the ArrayList
after three elements
have been added.
The references are added in order starting will cell 0 of the array.
import java.util.* ; class ArrayListEg { public static void main ( String[] args) { // Create an ArrayList that holds references to Object ArrayList<Object> names = new ArrayList<Object>(); // Add three Object references names.add("Amy"); names.add("Bob"); names.add("Cindy"); // Access and print out the three 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) ); } }
Then the program accesses the references using the get()
method
and prints out the Strings
.
The output of the program is:
element 0: Amy element 1: Bob element 2: Cindy
The argument to the get()
method acts like an index into an array.
Assume that the following is added after the last statement of the program:
names.add("Daniel");
Where will the reference to "Daniel" be added?