ArrayLists and Iterators

Read this chapter about lists and the useful methods that are available for adding and inserting elements into a list. 

12. Setting ArrayList Elements


Answer:

size: 0 new size: 3 element 0: Amy element 1: Bob element 2: Cindy

Setting ArrayList Elements

The add(E elt) method adds to the end of an ArrayList. But sometimes you want to change the element at a particular index.

set( int index, E elt )

The element previously at index is replaced with the reference elt. The index should be in the range 0 to size-1.

An IndexOutOfBoundsException is thrown if the index is out of bounds. (For now, this means that the program will halt.)

The index must be in the range 0 to size-1, which are the indexes of cells already occupied. This method can't "skip over" empty cells when it adds an element. It can't be used to make a list that has gaps in it.

The program first builds a list of three elements, then replaces the element at index zero. 


import java.util.* ;                
public class ArrayListEgThree
{

  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 Objects
    for ( int j=0; j<names.size(); j++ )
      System.out.println("element " + j + ": " + names.get(j) );

    // Replace "Amy" with "Zoe"
    names.set(0, "Zoe");
    System.out.println();
    
    // Access and print out the Objects
    for ( int j=0; j<names.size(); j++ )
      System.out.println("element " + j + ": " + names.get(j) );
    
  }
}


Question 12:

What does the program print out?

element 0:
element 1:
element 2:

element 0:
element 1:
element 2: