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?

Answer:

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
    names.add("Amy");
    names.add("Bob");
    names.add("Cindy");
    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.

QUESTION 11:

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