Setting ArrayList Elements

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

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 a ArrayList. Sometimes you want to change the data at a particular index.

set( int index, E elt )

The data previously at index is replaced with reference. 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.


import java.util.* ;

class ArrayListEgThree
{

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

    // Add Object 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) );
    
  }
}

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

QUESTION 12:

What does the program print out?

slot 0:
slot 1:
slot 2:

slot 0:
slot 1:
slot 2: