Example Program Continued

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:

The list will hold references to Integer objects.

Example Program Continued

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 with 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.

QUESTION 6:

Assume that the following is added after the last statement of the program:

    names.add("Daniel");

Where will the reference to "Daniel" be added?