Generic Array Lists (J2SE 5.0)

The ArrayList class allows dynamic storage of specifically typed Java objects, automatically adjusting its capacity as you add and remove elements. (Core Java, p. 180). An ArrayList is a generic class with a type parameter and can be expressed as follows:

ArrayList<Employee> staff = new ArrayList<Employee>();   

The above statement declares and constructs an array list that holds Employee objects.

Objects can be added to the array list as shown:

staff.add(new Employee("Joe Smith",...);   

The specifically typed ArrayList will not allow objects of other unrelated types to be stored. The statement

staff.add(new Date());   

will be reported as an error by the compiler.

 

To retrieve objects already store in the array, use:

Employee e = staff.get(i);   

 

You may cast an ArrayList<Employee> to an ArrayList, although it defeats the type checking provided by the generic class.. You will receive compiler warnings when you attempt to cast an ArrayList to an ArrayList<Employee>.

Next...                                                                                                                                page 3-14