You can encapsulate your integers in Integer objects
and store them in an ArrayList.
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 Strings.
The statement
ArrayList<String> names = new ArrayList<String>();
creates an ArrayList of String references.
The phrase <String> can be read as "of String references".
There are "angle brackets" on each side of <String>.
The phrase ArrayList<String> describes both the type of the
object (an ArrayList) and the type of data it
holds (references to String).
names.add("Amy")adds a reference to "Amy" to the next open position innames, index 0 to start.
names.get(0)returns the reference in the cell atindex0.
ArrayList is a generic type.
Its constructor
specifies both the type of object to construct
and the type of data it holds.
The type of data 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.
Examine the following:
ArrayList<Integer> values = new ArrayList<Integer>();
What type of data will values hold?