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

Say that you have an ArrayList of references to String. What does the add() method look like?


boolean add(String o)

Adding Elements to an ArrayList

ArrayList implements the List<E> Interface. To add an element to the end of an ArrayList use:

boolean add( E elt ) ;   // Add a reference to an object elt to the end of the ArrayList,
                         // increasing size by one.  The capacity will increase if needed.
                         // Always returns true.

To access the element at a particular index use:

E get( int index )

The method returns a reference to an object of the type E of the list. Here our example program, where the type in the list is String.

import java.util.* ;

class ArrayListEgTwo

  public static void main ( String[] args)
    // Create an ArrayList that holds references to String
    ArrayList<String> names = new ArrayList<String>();

    // Capacity starts at 10, but size starts at 0
    System.out.println("initial size: " + names.size() );

    // Add three String references
    System.out.println("new size: " + names.size() );
    // Access and print out the Objects
    for ( int j=0; j<names.size(); j++ )
      System.out.println("element " + j + ": " + names.get(j) );

This program creates n ArrayList of references to String objects. The for statement uses size() for the upper bound of the loop. This works because there are never any empty cells between the elements of the list.


What does the program print out?
new size:
element 0: 
element 1: 
element 2: