0: Zoe 1: Bart 2: Chris
Frequently you wish to remove an element
from a list.
The Vector
class has a method that will do this without leaving
a hole in place of the deleted element:
removeElementAt(int index) // Deletes the element atindex
. Each element with an index // greater thanindex
is shifted downward to have an index // one smaller than its previous value.
The element at location index will be eliminated. Elements at locations index+1, index+2, ... , size()-1 will each be moved down one to fill in the gap. This is like pulling out a book from the middle of a stack of books.
Examine the following program. What will it print?
import java.util.* ;
class VectorEg
{
public static void main ( String[] args)
{
Vector names = new Vector( 10 );
names.addElement( "Amy" );
names.addElement( "Bob" );
names.addElement( "Chris" );
names.addElement( "Deb" );
names.removeElementAt(2);
for ( int j=0; j < names.size(); j++ )
System.out.println( j + ": " +
names.elementAt(j) );
}
}