img
lists are created with an initial size. When this size is exceeded, the collection is automatically
enlarged. When objects are removed, the array can be shrunk.
NOTE  Dynamic arrays are also supported by the legacy class Vector, which is described later
OTE
in this chapter.
ArrayList has the constructors shown here:
ArrayList( )
ArrayList(Collection<? extends E> c)
ArrayList(int capacity)
The first constructor builds an empty array list. The second constructor builds an array list
that is initialized with the elements of the collection c. The third constructor builds an array
list that has the specified initial capacity. The capacity is the size of the underlying array that
is used to store the elements. The capacity grows automatically as elements are added to an
array list.
The following program shows a simple use of ArrayList. An array list is created for objects
of type String, and then several strings are added to it. (Recall that a quoted string is translated
into a String object.) The list is then displayed. Some of the elements are removed and the
list is displayed again.
// Demonstrate ArrayList.
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
// Create an array list.
ArrayList<String> al = new ArrayList<String>();
System.out.println("Initial size of al: " +
al.size());
// Add elements to the array list.
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " +
al.size());
// Display the array list.
System.out.println("Contents of al: " + al);
// Remove elements from the array list.
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " +
al.size());
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home