ArrayList<String> names = new ArrayList<String>();
This creates an ArrayList
with cells that point to String
objects.
ArrayList<E>
(Review)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 ArrayList
in the above program (from chapter 85) holds references to String
objects.
The Java API includes ArrayList<E>
,
which is a generic class.
The E
in this expression is a type variable.
This specifies the type of object the ArrayList
will hold.
The value given to the type variable must be a type of object (a class.)
For example, these statements construct ArrayList
s that hold
(references to) different classes of objects:
ArrayList<String> names = new ArrayList<String>(); ArrayList<String> data = new ArrayList<Integer>(); ArrayList<String> sizes = new ArrayList<Double>(); ArrayList<String> accounts = new ArrayList<MyType>();
Each declaration uses the class ArrayList<E>
from the java.util
package,
but tailors it to work with the specified class.
(Trick Question:) Is the following statement likely to work?
ArrayList<int> intList = new ArrayList<int>();