Adding at a Specific Index

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:

slot 0: Amy
slot 1: Bob
slot 2: Cindy
slot 0: Zoe
slot 1: Bob
slot 2: Cindy

Adding at a Specific Index

You can insert an element at a specific index from 0 ... size()-1. The newly added element is now located at the specified index, and all elements above that element have their index increased by one.

void add(int index, E elt)  //  Inserts the element at index. Each element with 
                            //  an index greater than index is shifted upward 
                            //  and now has an index one greater than its previous value. 

The method throws an IndexOutOfBoundsException if the index is out of bounds. No "gaps" in the list can be created by using this method. The following program uses this method:

import java.util.* ;

class ArrayListEgFour
{

  public static void main ( String[] args)
  {
    ArrayList<String> names = new ArrayList<String>();

    names.add( "Amy" );
    names.add( "Bob" );
    names.add( "Chris" );

    // Print original arrangement
    System.out.println("Before adding at index 1:");
    for ( int j=0; j < names.size(); j++ )
      System.out.println( j + ": " + names.get(j) ); 
      
    // Insert an element
    names.add( 1, "Valerie");

    // Print new arrangement
    System.out.println("/nAfter adding at index 1:");
    for ( int j=0; j < names.size(); j++ )
      System.out.println( j + ": " + names.get(j) ); 

  }
}

The program prints out:

Before adding at index 1:
0: Amy
1: Bob
2: Chris

After adding at index 1:
0: Amy
1: Valerie
2: Bob
3: Chris

QUESTION 13:

Would the following statement work in the above program?

names.add(5, "Gertrude");