You are on page 1of 5

ArrayList

The ArrayList class extends AbstractList and implements the List interface. ArrayList
supports dynamic arrays that can grow as needed. In Java, standard arrays are of a fixed length.
After arrays are created, they cannot grow or shrink, which means that you must know in
advance how many elements an array will hold. But, sometimes, you may not know until run
time precisely how large of an array you need. To handle this situation, the collections
framework defines ArrayList. In essence, an ArrayList is a variable-length array of object
references. That is, an ArrayList can dynamically increase or decrease in size. Array lists are
created with an initial size. When this size is exceeded, the collection is automatically enlarged.
When objects are removed, the array may be shrunk.

ArrayList has the constructors shown here:


ArrayList( )
ArrayList(Collection 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, and then
objects of type String 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 al = new ArrayList();
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());
System.out.println("Contents of al: " + al); // display the array list
// Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}

Although the capacity of an ArrayList object increases automatically as objects are stored in it,
you can increase the capacity of an ArrayList object manually by calling ensureCapacity( ).
You might want to do this if you know in advance that you will be storing many more items in
the collection that it can currently hold. By increasing its capacity once, at the start, you can
prevent several reallocations later. Because reallocations are costly in terms of time, preventing
unnecessary ones improves performance. The signature for ensureCapacity( ) is shown here:

void ensureCapacity(int cap)

Here, cap is the new capacity. Conversely, if you want to reduce the size of the array that
underlies an ArrayList object so that it is precisely as large as the number of items that it is
currently holding, call
trimToSize( ), shown here:

void trimToSize( )

Obtaining an Array from an ArrayList

When working with ArrayList, you will sometimes want to obtain an actual array that contains
the contents of the list. As explained earlier, you can do this by calling toArray( ). Several
reasons exist why you might want to convert a collection into an array such as:

• To obtain faster processing times for certain operations.


• To pass an array to a method that is not overloaded to accept a collection.
• To integrate your newer, collection-based code with legacy code that does not understand
collections.

Whatever the reason, converting an ArrayList to an array is a trivial matter, as the following
program shows:

// get array
Object ia[] = al.toArray();
int sum = 0;
// sum the array
for(int i=0; i<ia.length; i++)
sum += ((Integer) ia[i]).intValue();
System.out.println("Sum is: " + sum);
}
}
Here are some of the most useful ArrayList methods. Assume these declarations. Note that E is the
notation for the type of an element in a collection. Sun recommends using single upper case letters for
generic types.

int i;
ArrayList<E> a;
E e;
Iterator<E> iter;
ListIterator<E> liter;
E[] earray;
Object[] oarray;

Result Method Description


Constructors
a = new ArrayList<E>() Creates ArrayList with initial default capacity 10.
a = new ArrayList<E>(cap) Creates ArrayList with initial int capacity cap.
a = new ArrayList<E>(coll<E>) Creates ArrayList from the Collection coll.
Adding elements
a.add(e) adds e to end of ArrayList a
a.add(i, e) Inserts e at index i, shifting elements up as necessary.
Replacing an element
a.set(i,e) Sets the element at index i to e.
Getting the elements
e = a.get(i) Returns the object at index i.
oarray = a.toArray() Returns values in array of objects.
earray = a.toArray(E[]) The array parameter should be of the E class. Returns values in
that array (or a larger array is allocated if necessary).
Iterators
iter = a.iterator() Returns an Iterator for forward traversal.
liter = a.listIterator(i) Returns a ListIterator for forward / backward / modifying
traversal, starting at index i. Start from end with
a.listIterator(a.size())
liter = a.listIterator() Returns a ListIterator for forward / backward / modifying
traversal.
Searching
b = a.contains(e) Returns true if ArrayList a contains e
i = a.indexOf(e) Returns index of first occurrence of e, or -1 if not there.
i = a.lastIndexOf(e) Returns index of last occurrence of e, or -1 if not there.
Removing elements
a.clear() removes all elements from ArrayList a
a.remove(i) Removes the element at position i.
a.removeRange(i, j) Removes the elements from positions i thru j.
Other
i = a.size() Returns the number of elements in ArrayList a.

EXAMPLES

Adding elements to the end of an ArrayList, getting them by index


ArrayList<E> a = new ArrayList<E>(); // Default size.
E s; // Declare s to be an object type E.
...
a.add(s); // Adds s to the end of the ArrayList a
...
s = a.get(i); // Assigns ith element from a to s.
To get successive elements from an ArrayList - Four ways

Use either a for loop with an integer index to get all the elements from an ArrayList, or go over
all elements in a ArrayList using an Iterator (forward) or ListIterator (forward / backward).

1. foreach loop. This is fast and works for all kinds of lists, but is not entirely flexible (only
sequential forward with no deletions, additions, or multiple references). This should be
your first choice in programming. Works efficiently with both ArrayList and LinkedList.
2. ArrayList<String> a = new ArrayList<String>();
3. ...
4. for (String s : a) {
5. System.out.println(s);
}

6. for loop with index. This is fast, but should not be used with a LinkedList. It does allow
orders other than sequentially forward by one.
7. for (int i = 0; i < a.size(); i++) {
8. System.out.println(a.get(i));
}

9. Iterator<E> - Allows simple forward traversal. Can be used for the largest number of other
kinds of data structures.

This example uses an Iterator to print all elements (Strings) in an ArrayList. It uses
hasNext(), which returns true if there are more elements, and next(), which returns the next
element. Works with both ArrayList and LinkedList.

for (Iterator<String> iter = a.iterator(); iter.hasNext(); ) {


System.out.println(iter.next());
}

10. ListIterator<E> - Allows traversal of the ArrayList, but it is more general than a simple
Iterator, allowing inserts and deletes (although both are very slow for an ArrayList). It
also allows bidirectional traversal. Works efficiently with both ArrayList and LinkedList.
Sorting

If the data in your ArrayList has a natural sorting order (ie, implements Comparable, as do
String, Integer, ...), you can simply call the static Collections.sort() method. This is a stable,
guaranteed n log n sort.

Collections.sort(yourArrayList);

If you want to choose a different sort criterion or your data doesn't implement xxxx, you will
have to define a Comparator and pass that to the sort() method.

Collections.sort(yourArrayList, yourComparator);

You might also like