ArrayLists and Iterators
11. Adding Elements to an ArrayList
Answer:
ArrayList<String> data = new ArrayList<String>(10);
Which of the following statements will work?
data.add( "Irene Adler" ); // OK
data.add( new String("Laura Lyons") ); // OK
data.add( 221 ); // wrong type of argument
data.add( new Integer( 221 ) ); // wrong type of argument
Adding Elements to an ArrayList
ArrayList
ArrayList
implements the List<E>
Interface.
To add an element to the end of an ArrayList
use:
// Add a reference to an object elt to the end of the ArrayList,
// increasing size by one. The capacity will increase if needed.
// Always returns true.
boolean add( E elt ) ;
To access the element at a particular index use:
E get( int index )
This method returns a reference to an object in the list, which is of type E
. Here is our example program, where type E
is String
.
import java.util.* ; public class ArrayListEgTwo { public static void main ( String[] args) { // Create an ArrayList that holds references to String ArrayList<String> names = new ArrayList<String>(); // Capacity starts at 10, but size starts at 0 System.out.println("initial size: " + names.size() ); // Add three String references names.add("Amy"); names.add("Bob"); names.add("Cindy"); System.out.println("new size: " + names.size() ); // Access and print out the Objects for ( int j=0; j<names.size(); j++ ) System.out.println("element " + j + ": " + names.get(j) ); } } |
ArrayList
of references to String
objects. The for
statement uses size()
for the upper bound of the loop. This works
because there are never any empty cells between the elements of the list.Question 11: