ArrayLists and Iterators
Read this chapter about lists and the useful methods that are available for adding and inserting elements into a list.
5. Example Program
Answer:
You can encapsulate your integers in Integer
objects and store them in an ArrayList
.
Example Program
import java.util.* ; public class ArrayListEg { public static void main ( String[] args) { // Create an ArrayList that holds references to String ArrayList<String> names = new ArrayList<String>(); // Add three String references names.add("Amy"); names.add("Bob"); names.add("Cindy"); // Access and print out the three String Objects System.out.println("element 0: " + names.get(0) ); System.out.println("element 1: " + names.get(1) ); System.out.println("element 2: " + names.get(2) ); } } |
The example program creates an ArrayList
that holds String
references and then adds references to three String
s. The statement
ArrayList<String> names = new ArrayList<String>();
creates an ArrayList
of String
references. The phrase <String>
can be read as "of String references". Note that there are "angle brackets" on each side of <String>
.
The phrase ArrayList<String>
describes both the type of the object that is constructed (an ArrayList
) and the type of data it will hold (references to String
).
ArrayList
is a generic type, which means that its constructor specifies both the type of object to construct and the type that the new object will hold. The type the object will hold is placed inside angle brackets
like this: <DataType>
. Now, when the ArrayList
object is constructed, it will hold data of type "reference to DataType".
A program must import the java.util
package to use ArrayList
.
By default, an ArrayList
starts out with 10 empty cells.
Question 5:
Examine the following:
ArrayList<Integer> values = new ArrayList<Integer>();
What type of data will
values
hold?