​​​​​​A Java ArrayList is a general-purpose resizeable array. It provides several useful features that operate on the data it contains. You can access elements using an index, perform CRUD operations, resize the array, and iterate over its elements.

To use an ArrayList in your program, you will first need to import the java.util.ArrayList package. This will provide access to the three ArrayList constructors, along with several methods. Some of the more popular ArrayList methods include add(), addAll(), set(), get(), indexOf(), and remove().

Subclasses of the AbstractList

The AbstractList class implements the List interface and gives you access to data structures such as an ArrayList. Other direct and indirect subclasses of the AbstractList include:

  • The LinkedList data structure supports fast insertion and removal at intermediate indices.
  • The Vector data structure is like an ArrayList, but synchronized. It's suitable to use in place of an ArrayList for multithreaded applications.
  • The Stack data structure supports operations for mimicking a last-in-first-out list. Naturally, it synchronizes because it extends the Vector class.
ArrayList Class Hierarchy from Java Collections

These special classes are outside the scope of this article. However, you will learn how to set up and use a general-purpose Java ArrayList.

Creating an ArrayList

Creating an ArrayList in Java is simple. You can create an empty ArrayList using the no-arguments constructor.

The following code creates an empty ArrayList for holding strings.

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

If you know how many items your array list will contain, you can specify the initial capacity. This initial capacity is just a hint for memory allocation. Whether you specify a capacity or not, the ArrayList has no memory restrictions. If you know and specify the initial capacity, you might get a slight performance improvement.

        ArrayList<String> alist = new ArrayList<String>(8);
    

The code above creates an ArrayList (alist) that allocates eight index positions in memory.

A new ArrayList with empty slots
A new ArrayList with empty slots

Populating an ArrayList

Adding Items at the End

Populating an ArrayList is quite easy. Just use the add() method to add a single item to the end of the ArrayList. Here is an example:

        ArrayList<String> alist = new ArrayList<String>();
alist.add("apple");
alist.add("banana");
alist.add("cantaloupe");
alist.add("orange");
System.out.println(alist);

The code above displays the following output in the console:

        [apple, banana, cantaloupe, orange]
    

The size() method returns the number of items in an ArrayList.

        System.out.println("Number of elements in the arraylist: " + alist.size());
// Prints
// Number of elements in the arraylist: 4
Adding Items to an ArrayList at the end.

Adding Items at a Specified Index

Want to add an item at a specific index position? Simply provide the add() method with the index position you want to use, followed by the item you want to add:

        alist.add(3, "grapes");
System.out.println(alist);

The code above displays the following output in the console:

        [apple, banana, cantaloupe, grapes, orange]
    

In the ArrayList above you will notice that "grapes" is fourth in the list. This is at index position three since a Java ArrayList begins at index position zero.

Adding a Bunch of Items

You can add items from any collection in the Java Collections hierarchy too. An ArrayList is a specific type called List. Here is a way to construct a List from a bunch of items (using Arrays.asList()) and add it to an ArrayList.

        List<String> items = Arrays.asList("pear", "cherry");
alist.addAll(items);
System.out.println(alist);
// prints
// [apple, banana, cantaloupe, grapes, orange, pear, cherry]

You can also provide an index as the first argument of the addAll() method. This will allow you to place the items List at any position in the ArrayList.

Accessing Items

After you add the items to an ArrayList, how do you access them again?

Accessing Items With an Index

If you know the item's index, you can use the get() method to retrieve the element at specific index position.

        String item = alist.get(2);
System.out.println("Item at index 2 is: " + item);
// prints
//Item at index 2 is: cantaloupe

Finding Items

What if you don't know the index of the item? You can use indexOf() to check if the item is present in the array and retrieve the item using the returned index.

        System.out.println(alist);
int index = alist.indexOf("orange");

if (index < 0) {
    System.out.println("Item \"orange\" not found");
} else {
    System.out.println("Item \"orange\" found at index " + index);
}
 
// prints
// [apple, banana, cantaloupe, grapes, orange, pear, cherry]
// Item "orange" found at index 4

The indexOf() method returns -1 when the program does not find an item:

        index = alist.indexOf("grape");
 
if (index < 0) {
    System.out.println("Item \"grape\" not found");
} else {
    System.out.println("Item \"grape\" found at index " + index);
}

// prints
// Item "grape" not found

Iterating Over an ArrayList

The most common use of an ArrayList is iterating over the elements. You can accomplish this in several ways. The following code contains a for loop that iterates over an ArrayList and prints each item in the console:

        for (String fruit : alist) {
    System.out.println("Found fruit \"" + fruit + "\"");
}
 
// prints
// Found fruit "apple"
// Found fruit "banana"
// Found fruit "cantaloupe"
// Found fruit "grapes"
// Found fruit "orange"
// Found fruit "pear"
// Found fruit "cherry"

Before Java's enhanced for loop developers would iterate over the items in an ArrayList with an iterator. An iterator can also remove elements during the process of iteration, as the example below illustrates. Note that the code below makes a copy of the ArrayList and works on the copy.

        ArrayList<String> blist = new ArrayList<String>(alist);
 
for (Iterator<String> iter = blist.iterator() ; iter.hasNext() ; ) {
    String fruit = iter.next();
 
    if (fruit.startsWith("c")) {
        iter.remove();
    } else {
        System.out.println("Keeping \"" + fruit + "\"");
    }
}
 
// prints
// Keeping "apple"
// Keeping "banana"
// Keeping "grapes"
// Keeping "orange"
// Keeping "pear"

Replacing Items

The set() method allows you to replace an existing item in an ArrayList. This method takes two arguments; the index position of the item you want to replace and the new item.

        alist.set(5, "pineapple");
System.out.println(alist);
// prints
// [apple, banana, cantaloupe, grapes, orange, pineapple, cherry]

Removing Items

If you know the index position of an item that you want to remove from a list, you can use the remove() method to achieve this. The remove() method takes an index position or an item as an argument.

        String fruit = alist.remove(2);
System.out.println("Removed element at 2: " + fruit);
// prints
// Removed element at 2: cantaloupe

The code below returns true if the program locates and removes the specified item.

        fruit = "grapes";
System.out.println("Remove " +fruit+ " from the list? " + alist.remove(fruit));
// prints
// Remove grapes from the list? true

The Value of Choosing the Right Data Structure

Knowing how to create and manipulate ArrayLists in Java is an invaluable skill. An ArrayList is one of several data structures that you can use to store data. So, it might not always be the best-suited data structure for what you want to accomplish.

For example, if you want to store your data with a unique key and the storage order is not important, then a HashMap is a better option than an ArrayList. It is, therefore, an asset to know how to use a wide variety of data structures.