Let’s take a look at a great data structure provided in Java – The ArrayList.

The ArrayList is a standard Java class which resides in the java.util package. In other words, you don’t have to add any libraries or dependencies to your project – the ArrayList is already there, or “pre-packaged” if you will.
The ArrayList is a dynamic array, which supports insertion and removal of objects. You can also search for objects in an ArrayList. But why should you use an ArrayList instead of the native array?

The native array in Java has very limited functionality.   Say, for example, that you want to expand your array. If you’re using a native array, there is no support for that. Of course, it is possible to implement a work-around, but it will be tedious and require extra work – and when you’re programming for a client, you don’t want that!
To further prove the need for the ArrayList, let’s say you want to remove a certain object from your list.
If you’re using a native array, you’ll have to manually loop through the entire array. And to complicate things even more, you’ll also have to shift the positions of every object previous to the object you removed. Something like this:

for (int i = 0; i < array.length; i++) {
 if (array[i].equals(objectToRemove)) {
   array[i] = null;
   break;
 } 
}

The above illustration does not include the logic to shift the positions. So, even more work on your part.. With an ArrayList, on the other hand:

myArrayList.remove(objectToRemove);

This is what makes the ArrayList so great. It has a whole lot of convenient methods, and will basically do all the heavy lifting for you.

Creating an ArrayList

Say you want to create an array, which stores a list of Strings. With a regular array, you would do this:

String [] stringArr = new String[10]

The number 10 signals that you want the array to be able to hold a total of 10 objects.
But we know better.. Let’s use an ArrayList:

ArrayList<String> stringArray = new ArrayList<String>();

Note that the last declaration, <String>, is redundant when using Java 7 or higher. Java 7 introduced the diamond operator, so the above statement is actually equivalent to:

ArrayList<String> stringArray = new ArrayList<>();

That’s about it. Notice how you don’t have to specify a size for your list. The ArrayList handles all this internally, and you never have to worry about “running out of space”.

Adding to an ArrayList

Let’s say you want to store a list of people invited to your birthday party. The ArrayList we created support String-objects, so this is perfectly fine. We’re assuming “John”, “Lian” and “Beth” are attending (hell of a party).
To add them to the list, we make use of the add() method of the ArrayList.

stringArray.add("John");
stringArray.add("Lian");
stringArray.add("Beth");

Removing objects from an ArrayList

There is actually two ways to remove objects from an ArrayList. If you know which position the object is at, you can pass this information to the remove() method. If you don’t know the position of the object, you can simply pass the object itself – the ArrayList will look for it, and remove the object if it’s in the array.
Remember that positions in an array always start at 0! Thus, the first object is at position 0.

So, to remove “John” from the list, which is in the first position (position 0), we do this:

stringArray.remove(0);

Otherwise, if we’d like to remove “John”, without knowing the objects position, we do it this way:

stringArray.remove(“John”);

Looping through an ArrayList

Now, as our last example, let’s say you want to have a look at all the people attending the party. You can do this in two different ways.
The “old school” method of doing this, is with a standard for loop. Let’s look at the code:

for (int i = 0; i < stringArray.size(); i++) {
   System.out.println(stringArray.get(i));
}

This is pretty straight forward. If you haven’t seen a for loop before, I encourage you to go and look it up!

The second way to loop (actually, iterate) through an ArrayList is with the enhanced for loop. The enhanced for loop makes use of an Iterator behind the scenes, and is even easier to implement than the for loop shown above.

for (String s : stringArray) {
    System.out.println(s);
}

What you’re basically saying is: For every String s in the stringArray, print it out! Pretty easy, eh?

Summary

In this article we talked about the ArrayList. The ArrayList is a dynamic array, and comes with a whole lot more functionality than a regular array does. The operations shown in this article is just a few out of many useful operations that the ArrayList supports.

If you’re curious about how the ArrayList works “under the hood”, I’ve written a simple implementation of an ArrayList. Most of the operations supported by the ArrayList in java.util are missing, but it’s great if you just want a feel for how it actually works. In fact, the ArrayList is just an abstracted regular array!
NB! If you want the enhanced for loop to work, you’ll have to implement an Iterator.

import java.util.Arrays;

/**
 * Simplified implementation of an ArrayList in Java.
 * <p>
 * This is inferior to the implementation in java.util,
 * and thus not meant to be used in any actual applications.
 *
 * @author Anders Engen Olsen.com
 */
public class SimplifiedArrayList<AnyType> {

    // The initial size of the array.
    // Remember, with ArrayLists you don't need to explicitly set the size.
    private static final int INIT_SIZE = 10;

    // Native Java array.
    private AnyType[] internalArray;

    // Internal counter for size of the SimplifiedArrayList
    private int arraySize;

    /**
     * Parameter-free constructor, constructing an empty array of type AnyType.
     * The size is set to INIT_SIZE
     */
    public SimplifiedArrayList() {
        this(INIT_SIZE);
    }

    /**
     * Constructor, constructing an internal array with given size
     *
     * @param size size of the array.
     */
    public SimplifiedArrayList(int size) {
        if (size < 0)
            throw new IllegalArgumentException("Size must be greater than 0");
        this.internalArray = (AnyType[]) new Object[size];

        arraySize = 0;
    }

    /**
     * Returning object in given index.
     *
     * @param index index of object to find.
     * @return object in position index.
     */
    public AnyType get(int index) {
        if (index > arraySize - 1 || index < 0)
            throw new IndexOutOfBoundsException("Array out of bounds");

        return internalArray[index];
    }

    /**
     * Adding object to the array.
     *
     * @param a object to add
     * @return true
     */
    public boolean add(AnyType a) {
        // Checking capacity if the internal array
        checkCapacity(arraySize + 1);
        // Adding to the array
        internalArray[arraySize++] = a;

        return true;
    }

    /**
     * Removing object from the array
     *
     * @param index index of object to remove
     * @return true
     */
    public boolean remove(int index) {
        if (index > arraySize || index < 0)
            throw new IndexOutOfBoundsException("Array out of bounds");

        // Fetching the object to remove.
        AnyType toRemove = internalArray[index];

        // Calculating new length
        int newLength = arraySize - index - 1;

        // Copying to a new array
        if (newLength > 0)
            System.arraycopy(internalArray, index + 1,
                    internalArray, index, newLength);

        // Setting to null, will be collected by the GarbageCollector
        internalArray[--arraySize] = null;

        // Returning removed object
        return true;
    }

    /**
     * VERY simplified implementation of remove-operation on an ArrayList.
     *
     * @param a object to remove
     * @return true if found
     */
    public boolean remove(AnyType a) {
        if (a == null)
            throw new IllegalArgumentException("Null not accepted");

        for (int i = 0; i < arraySize; i++) {
            if (internalArray[i].equals(a))
                return remove(i);
        }

        return false;
    }

    /**
     * Returning the number of elements in the internal array
     *
     * @return size
     */
    public int size() {
        return arraySize;
    }

    /**
     * Checking the capacity of the internal array.
     * If the array is full, we expand it by doubling it's size.
     */
    private void checkCapacity(int size) {
        if (size == internalArray.length) {
            // Creating new array, twice the size.
            int previousSize = internalArray.length;
            int newSize = previousSize * 2;
            internalArray = Arrays.copyOf(internalArray, newSize);
        }
    }
}