# Java Notes: ArrayList (non-generic)

`java.util.ArrayList` allows for expandable arrays, and is the Collections replacement for the older Vector class. An ArrayList has the following advantages over an array:

- An ArrayList automatically expands as data is added.
- Access to any element of an ArrayList is O(1). Insertions and deletions are O(N).
- An ArrayList has methods for inserting, deleting, and searching.
- An ArrayList can be traversed using either iterators or indexes.

Automatic expansion. Use ArrayList when there will be a large variation in the amount of data that you would put into an array. Arrays should be used only when there is a constant amount of data. For example, storing information about the days of the week should use an array because the number of days in a week is constant. Use an array list for your email contact list because there is no upper bound on the number of contacts.

Objects only. A disadvantage of a ArrayList is that it holds only objects and not primitive types (eg, `int`). To use a primitive type in an ArrayList, put it inside an object (eg, to save an integer value use the `Integer` class or define your own class). If you use the Integer wrapper, you will not be able to change the integer value, so it is sometimes useful to define your own class.

Implementation. ArrayLists are implemented with an underlying array, and when that array is full and an additional element is added, a new array is allocated and the elements are copied from the old to the new. Because it takes time to create a bigger array and copy the elements from the old array to the new array, it is a faster to create an ArrayList with a size that it will commonly be when full. Of course, if you knew the final size, you could simply use an array. However, for non-critical sections of code programmers typically don't specify an initial size.

## Constructors

    ArrayList alist1 = new ArrayList();    // Created with default size.
    ArrayList alist2 = new ArrayList(300); // Starts with 300 elements

## To Add elements to the end of an ArrayList

    a.add(s); // adds s to the end of the ArrayList a

## To get the elements from an ArrayList

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).

- `for` loop with index - this is the fastest method, but will need to be changed you later decide to change to a LinkedList structure.
- `ListIterator` - Allows traversal of the ArrayList, and allows inserts and deletes (although both are very slow for an ArrayList). It also allows bidirectional traversal. Can be used if the data structure is later changed.
- `Iterator` - 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 as an Object, which must be downcast to the appropriate type (until Java 1.5 additions).

    // Without Java 5 generics.
    for (Iterator iter = a.iterator(); iter.hasNext();) {
        System.out.println((String)(iter.next()));
    }

The following is faster, but less general:

    // Without Java 5 generics.
    for (int i = 0; i < a.size(); i++) {
        System.out.println((String)(a.get(i)));
    }

## 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);

Check out Collections for other useful utility methods.

## Common ArrayList methods and constructors

Here are some of the most useful ArrayList methods. `a` is an ArrayList, `i` is an int, `obj` is an Object, `iter` is an Iterator, `liter` is a ListIterator.

Result | Method | Description
--- | --- | ---
Constructors
`a =` | `new ArrayList()` | Creates ArrayList with initial default capacity 10.
`a =` | `new ArrayList(cap)` | Creates ArrayList with initial int capacity cap.
`a =` | `new ArrayList(coll)` | Creates ArrayList from the Collection coll.
Adding elements
`` | `a.add(obj)` | adds `obj` to end of ArrayList `a`
`` | `a.add(i, obj)` | Inserts `obj` at index `i`, shifting elements up as necessary.
Replacing an element
`` | `a.set(i,obj)` | Sets the element at index `i` to `obj`.
Getting the elements
`obj =` | `a.get(i)` | Returns the object at index `i`.
`oarray =` | `a.toArray()` | Returns values in array.
`oarray =` | `a.toArray(Object[])` | The array parameter can be any Object subclass (eg, String). This returns values in that array (or a larger array 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(obj)` | Returns true if ArrayList `a` contains `obj`
`i =` | `a.indexOf(obj)` | Returns index of first occurrence of `obj`, or -1 if not there.
`i =` | `a.lastIndexOf(obj)` | Returns index of last occurrence of `obj`, 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`.