ArrayLists and Iterators
14. Removing an Element
Answer:
No. You are not allowed to create gaps between elements. Adding an element at index 5 in the above program would generate a runtime error.
Removing an Element
To remove an element from a list use the remove()
method. This method removes an element without leaving a hole. The object references above the removed element are moved down to fill the gap.
E remove(int index) // Delete the element atindex
. Each element with an index
// greater thanindex
is shifted downward to have an index
// one smaller than its previous value.
// Returns a reference to the removed element.
// Throws anIndexOutOfBoundsException
if the index is out
// of range.
The object reference at location index
is removed from the list. Elements at locations index+1, index+2, ... , size()-1
are each moved down one to fill in the gap. This is like pulling out a book from the
middle of a stack of books.
The object reference that was removed from the list is the return value of the method. This value can be assigned to a reference variable. As long as there is a reference to the object, the object is not lost. If the only reference to the object was the one in the list, and that reference is not assigned to a variable, then the object will be garbage collected.
Question 14:
Examine the following program. What will it print?
import java.util.* ;
public class DeleteEg
{
public static void main ( String[] args)
{
ArrayList<String> names = new ArrayList<String>();
names.add( "Amy" );
names.add( "Bob" );
names.add( "Chris" );
names.add( "Deb" );
names.remove(2);
for ( int j=0; j < names.size(); j++ )
System.out.println( j + ": " + names.elementAt(j) );
}
}