ArrayLists and Iterators
Read this chapter about lists and the useful methods that are available for adding and inserting elements into a list.
13. Adding at a Specific Index
Answer:
element 0: Amy
element 1: Bob
element 2: Cindy
element 0: Zoe
element 1: Bob
element 2: Cindy
Adding at a Specific Index
You can insert an element at a specific index from 0
to size()
. The newly added element is now located at the specified index, and the indexes of all elements above that element is increased by one. If you
add an element at index size()
, the element is appended to the end of the list.
void add(int index, E elt) // Inserts the element atindex
. Each element with
// an index greater thanindex
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, either negative or greater than size()
. This prevents you from creating a list with gaps between elements. The following program
uses this method:
import java.util.* ; public 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");