slot 0: Amy slot 1: Bob slot 2: Cindy slot 0: Zoe slot 1: Bob slot 2: Cindy
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 atindex
. Each element with // an index greater thanindex
is shifted upward // to have 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
Would the following statement work in the above program?
names.add(5, "Gertrude");